# -*- mode: yaml; indent-tabs-mode: nil; tab-width: 2; coding: utf-8-unix -*-

---

- name: "proxy main.yml CORP_NTLM_PROXY={{ CORP_NTLM_PROXY | default('') }}"
  debug:
    verbosity: 1
    msg: "DEBUG: Including proxy main.yml"

- name: include proxy by-platform vars
  include_vars: "{{item}}.yml"
  with_items:
    - Unix
    - "{{ ansible_distribution }}{{ ansible_distribution_major_version }}"
  tags: always

- name: "rsync proxy root_overlay"
  synchronize:
    src: "roles/proxy/overlay/{{item}}/"
    dest: /
    compress: no
    copy_links: yes
    archive: no
    recursive: yes
    links: no
    owner: no
    perms: no
    times: yes
    rsync_opts: "{{base_rsync_opts}}"
  with_items:
    - Linux
    - "{{ ansible_distribution }}"
  notify:
#?    - chmod /usr/local
    - update-ca-certificates
  when:
    - not ansible_check_mode
    # FixAns: This remote host is being accessed via chroot instead so it cannot work
    - ansible_connection|default('') not in PLAY_NORSYNC_CONNECTIONS
  tags:
    - always

- name: rsync root_overlay - the tar gets made by a make before running
  unarchive:
    dest: /
    src: "{{item}}.tar"
    keep_newer: true
    owner: "{{BOX_ROOT_USER}}"
    # extra_opts: "{{ BASE_UNTAR_ARGS }}"
  ignore_errors: true
  with_items:
    - Linux
    - "{{ ansible_distribution }}"
  notify:
#?    - chmod /usr/local
    - update-ca-certificates
  when:
    - not ansible_check_mode
    # FixAns: This remote host is being accessed via chroot instead so it cannot work
    - ansible_connection|default('') in PLAY_NORSYNC_CONNECTIONS

- name: "grep -q root=/dev/vda /proc/cmdline "
  environment: "{{ shell_proxy_env }}"
  shell: |
    grep -q root=/dev/vda /proc/cmdline
  failed_when: false
  register: proxy_vda_cmdline_fact
  tags:
    - always

- name: proxy post tasks first
  include_tasks: "proxy_mode.yml"

# We are running these tasks here to set the proxy up to download and install packages
- name: proxy post tasks first
  include_tasks: "proxy_post.yml"

- name: include proxy by-platform tasks
  include_tasks: "{{ ansible_distribution }}.yml"

- name: "proxy gpg keys system"
  # Option --keyserver must be used to
  environment: "{{ shell_proxy_env }}"
  shell: |
    /usr/bin/gpg --list-keys | grep "{{ item.uid }}" || \
      /usr/bin/gpg --recv-keys "{{ item.uid }}"
      # --keyserver "{{ TESTF_GPG_SERVER }}"
      # deprecated - please use the --keyserver in ?dirmngr.conf? instead
  with_items: "{{ proxy_gpg_keys_system }}"
  when:
    - proxy_gpg_keys_system|length > 0
    - BASE_ARE_CONNECTED|default('') != ''
  # FixMe:
  ignore_errors: true

- name: fix pip
  shell: |
    find /usr/local/lib*/python*/*-packages/pip \
         -name filesystem.py | while read file ; do
         [ -f $file.dst ] && continue
         cp -p $file $file.dst
         sed -e 's/path_uid == 0/os.access(path, os.W_OK)/' -i $file
      done
    exit 0

- block:

  - name: /usr/local/patches/proxy
    shell: |
      [ -d /usr/local/patches/proxy/ ] || exit 0
      cd /usr/local/patches/proxy/ || exit 1
      ls || exit 2
      /usr/local/sbin/base_patch_from_diff.bash *

  when:
    - false and ansible_distribution == 'Gentoo'

- name: install proxy pips 2
  changed_when: false
  environment: "{{pip_proxy_env}}"
  pip:
    executable: "{{BASE_USR_LOCAL}}/bin/pip2.sh"
    state: present
    extra_args: "{{BASE_PIP_INSTALL_ARGS}} --log {{BASE_LOG_DIR}}/pip/pip2/proxy.log"
    name: "{{ proxy_pips2_inst }}"
  become: yes
  become_user: "{{ BOX_USER_NAME }}"
  notify: shebang after pip
  when:
    - false
    # this must be empty aas shebang after pip is in testforge
    - proxy_pips2_inst|length > 0
    - BASE_ARE_CONNECTED|default('') != ''
    - "BASE_PYTHON2_MINOR != ''"
  ignore_errors: "{{ base_pip_ignore_errors }}"

- name: install proxy pips 3
  changed_when: false
  environment: "{{pip_proxy_env}}"
  pip:
    executable: "{{BASE_USR_LOCAL}}/bin/pip3.sh"
    state: present
    extra_args: "{{BASE_PIP_INSTALL_ARGS}} --log {{BASE_LOG_DIR}}/pip/pip3/proxy.log"
    name: "{{ proxy_pips3_inst }}"
  become: yes
  become_user: "{{ BOX_USER_NAME }}"
  notify: shebang after pip
  when:
    - false
    # this must be empty aas shebang after pip is in testforge
    - proxy_pips3_inst|length > 0
    - BASE_ARE_CONNECTED|default('') != ''
  ignore_errors: "{{ base_pip_ignore_errors }}"

- name: "/usr/local/etc/local.d/Whonix-Lati.rc"
  blockinfile:
    dest: /usr/local/etc/local.d/Whonix-Lati.rc
    create: yes
    mode: 0770
    marker: "# {mark} ANSIBLE MANAGED BLOCK proxy main.yml start"
    insertafter: EOF
    block: |
      grep -q root=/dev/vda /proc/cmdline
      PROXY_IS_VDA=$?

#?  # this should not run as root
- name: "/usr/local/src/usr_local_python.bash"
  environment: "{{ shell_proxy_env }}"
  shell: |
    umask 0002
    [ ! -f  usr_local_proxy.bash ] && exit 1
    bash usr_local_python.bash \
      {{ 'check' if ansible_check_mode }}
  args:
    chdir: "{{PROXY_USR_LOCAL}}/src"
  become: yes
  become_user: "{{ BOX_USER_NAME }}"
  check_mode: false
  # FixMe:
  ignore_errors: true

  # this should be run as root
- name: run usr_local_src item
  environment: "{{ shell_proxy_env }}"
  shell: |
    umask 0002
    bash /usr/local/src/{{item}}.bash
  args:
    chdir: "{{ PROXY_USR_LOCAL }}/src"
  when:
    - item != '' and item != []
  with_items:
#    - "{{ 'sdwdate' if ansible_distribution == 'Gentoo' else '' }}"
    - []

- name: "enable and start services"
  service:
    name: "{{ item }}"
    enabled: yes
    state: restarted
  failed_when: false
  when:
    - "item != ''"
    - ansible_connection|default('') not in PLAY_NOSERVICE_CONNECTIONS
  with_items: "{{ proxy_services }}"

# We are running these tasks here to work around handler issues with include_tasks
- name: "proxy post tasks end"
  include_tasks: "proxy_post.yml"

- name: "proxy dirmngr tasks end"
  include_tasks: "dirmngr.yml"
  when:
    - "http_proxy != '' or https_proxy != '' or socks_proxy != ''"

- name: "whonix host tasks end"
  include_tasks: "{{LOOP_FILE}}.yml"
  when:
    - LOOP_FILE != '' and LOOP_FILE != []
    - ansible_connection|default('') not in PLAY_CHROOT_CONNECTIONS
  with_items:
    - "{{ 'whonix_host' if (PROXY_MODE == 'whonix' and BOX_WHONIX_PROXY_HOST != '' ) else [] }}"
  loop_control:
    loop_var: LOOP_FILE

- name: "whonix guest tasks end"
  include_tasks: "whonix_guest.yml"
  when:
    - "PROXY_MODE in ['gateway','ws', 'vda', 'nat']"
    # works?
    - ansible_virtualization_role|replace('NA', 'host') == 'guest'

- name: "include_tasks proxy users.yml"
  include_tasks:
    file: "users.yml"
    apply:
      environment: "{{ proxy_env }}"
      become_user: "{{ LOOP_USER }}"
  when:
    - LOOP_USER != [] and LOOP_USER != ''
  with_items:
    # FixMe: need user groups fixing
    - root
    - "{{ base_system_users }}"
    - "{{ proxy_also_users }}"
    - "{{ 'portage' if ansible_distribution == 'Gentoo' else '' }}"
  loop_control:
    loop_var: LOOP_USER

- name: /usr/local/etc/testforge/testforge.ini proxy
  blockinfile:
    dest: /usr/local/etc/testforge/testforge.ini
    create: yes
    marker: "# {mark} ANSIBLE MANAGED BLOCK ini [proxy]"
#?          PROXY_VAR_LOCAL={{PROXY_VAR_LOCAL}}
    block: |
      [proxy]
          HTTP_PROXYHOST="{{ HTTP_PROXYHOST }}"
          HTTP_PROXYPORT={{HTTP_PROXYPORT}}
          HTTP_PROXYTYPE="{{ HTTP_PROXYTYPE }}"
          HTTPS_PROXYHOST="{{ HTTPS_PROXYHOST }}"
          HTTPS_PROXYPORT={{HTTPS_PROXYPORT}}
          HTTPS_PROXYTYPE="{{ HTTPS_PROXYTYPE }}"
          SOCKS_PROXYHOST="{{ SOCKS_PROXYHOST }}"
          SOCKS_PROXYPORT={{SOCKS_PROXYPORT}}
          SOCKS_PROXYTYPE="{{ SOCKS_PROXYTYPE }}"
          NO_PROXY="{{ NO_PROXY }}"
          CORP_PROXY_PAC="{{ CORP_PROXY_PAC|default('') }}"
          CORP_NTLM_PROXY="{{ CORP_NTLM_PROXY|default('') }}"
          PROXY_FEATURES={{ PROXY_FEATURES }}
          PROXY_DNS_PROXY="{{ PROXY_DNS_PROXY }}"
          PROXY_DNS_NETMAN="{{ PROXY_DNS_NETMAN }}"
          PROXY_HTTP_PROXY_NAME="{{ PROXY_HTTP_PROXY_NAME|default('privoxy')}}"
          PROXY_HTTP_PROXY_PORT="{{ PROXY_HTTP_PROXY_PORT|default(3128)}}"
          PROXY_HTTP_PROXY_HOST="{{ PROXY_HTTP_PROXY_HOST|default('127.0.0.1')}}"

  notify: update facts
#? PLAY_PIP_CACHE="{{BASE_USR_LOCAL}}/net/Cache/Pip"

- name: /usr/local/etc/testforge/testforge.ini proxy gitconfig
  blockinfile:
    dest: /usr/local/etc/testforge/testforge.ini
    create: yes
    marker: "# {mark} ANSIBLE MANAGED BLOCK proxy main.yml"
    block: |
      [gitconfig]
          # FixMe: this may not be needed
          GIT_ALLOW_PROTOCOL="https"
          # This may not be needed if you put it in ~/.gitconfig
          GIT_SSL_CAINFO="/usr/local/etc/ssl/cacert-testforge.pem"
  # FixMe: this may not be needed
  # GIT_PROTOCOL_COMMAND="/usr/local/bin/gitproxy.bash"
  when:
    - true or CORP_NTLM_PROXY|default('') != ''
  notify: update facts

- block:

  - name: external
    delegate_to: localhost
    shell: |
      grep ' external$' /etc/hosts | sed -e 's/ .*//'
    register: external_out
    check_mode: false
    
  - name: BASE_EXTERNAL_IP
    set_fact:
      BASE_EXTERNAL_IP: "{{external_out.stdout}}"
    when: external_out.rc|default(1) == 0
    check_mode: false
    
  when:
    - "ansible_virtualization_role|replace('NA', 'host') == 'guest'"
    - BOX_OS_FLAVOR|default('') in [ 'WhonixWorkstation', 'WhonixGateway', 'Gentoo']

- name: "include dns.yml tasks"
  include_tasks: "dns.yml"
  when:
    - PROXY_DNS_PROXY != ''

- name: "include wicd.yml tasks"
  include_tasks: "wicd.yml"
  when:
    - false
    
- name: "find listening sockets for daily"
  environment: "{{ shell_proxy_env }}"
  shell: |
    netstat -t inet -npl | grep LISTEN
  register: proxy_netstat_nlp_fact
  failed_when: false
  tags:
    - always

- name: proxy hourly include_tasks
  include_tasks:
    file: "hourly.yml"
    apply:
      environment: "{{ shell_proxy_env }}"
      tags:
        - always
  tags:
    - always

# maybe should be in testforge but may use them early

- stat: path=/etc/java-config-2/current-system-vm/jre/lib/net.properties
  register: etc_x11_xsession_d
  when:
    - not ansible_check_mode

- name: "check arp length"
  environment: "{{ shell_proxy_env }}"
  shell: |
    a=`arp -i wlan7|tail -n -1|wc -l`
    [ $? -eq 0 ] || exit 1
    [ $a -eq 1 ] || exit $a
    exit 0

- name: "dnscrypt-proxy address already in use"
  shell: |
    tail -100 '{{PROXY_VAR_LOCAL}}/var/log/dnscrypt-proxy.log' | grep -q 'bind: address already in use' || \
       { echo 'ERROR: dnscrypt-proxy address already in use' ; exit 1 ; }
  when:
    - not ansible_check_mode
    - PROXY_DNS_PROXY == "dnscrypt"
    - PROXY_DNS_PORT != ''
    - BASE_ARE_CONNECTED|default('') != ''
    - testforge_netstat_nlp_fact is defined

# FixMe: /etc/systemd/system/sntp.service.d/00gentoo.conf
- name: /etc/ntp.conf
  blockinfile:
    dest: /etc/ntp.conf
    marker: "# {mark} ANSIBLE MANAGED BLOCK testforge"
    mode:  0640
    owner: "{{BOX_ROOT_USER}}"
#    group: ntp
    create: yes
    block: |
      # conf.d interface ignore all wlan7

      # If you want to deny all machines (including your own)
      # from accessing the NTP server, uncomment:
      restrict default ignore

      # Default configuration:
      # - Allow only time queries, at a limited rate, sending KoD when in excess.
      # - Allow all local queries (IPv4, IPv6)
      #restrict default nomodify nopeer noquery limited kod
      restrict 127.0.0.1
      restrict [::1]

      # You do need to talk to an NTP server or two (or three).
      {% for elt in PROXY_NTP_SERVERS %}
      server {{ elt }}
      {% endfor %}
    # {{ PROXY_NTP_SERVERS|join('\n') }}
  when:
    - "BOX_TIME_DAEMON == 'ntp'"

- name: apt-get update
  raw: |
    [ -f /var/log/dpkg.log ] || apt-get update
  when:
    - ansible_distribution in ['Ubuntu', 'Debian', 'Deuvan']
    - BASE_ARE_CONNECTED|default('') != ''
  ignore_errors: true
  check_mode: false

- name: base gpg keys system
  # Option --keyserver must be used to
  environment: "{{ shell_env }}"
  shell: |
    /usr/bin/gpg --list-keys | grep "{{ item.uid }}" || \
      /usr/bin/gpg --recv-keys "{{ item.uid }}" --keyserver "{{ BASE_GPG_SERVER }}"
  with_items: "{{ base_gpg_keys_system }}"
  when:
    - proxy_gpg_keys_system|length > 0
    - BASE_ARE_CONNECTED|default('') != ''
  # FixMe:
  ignore_errors: true

