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

---

- hosts: "{{ BOX_HOST }}" # |default('localhost')
#??  become: "{{ 'false' if ansible_connection|default('') == 'chroot' else 'true'}}"
#  become_method: "'' if ansible_connection|default('') == 'chroot' else 'sudo'"
  gather_facts: true
  vars:
    PLAY_CHROOT_CONNECTIONS: ['chroot', 'lxc', 'lxd', 'local'] #?
    PLAY_NOSERVICE_CONNECTIONS: ['chroot', 'lxc', 'lxd', 'local'] #?
    PLAY_NORSYNC_CONNECTIONS: ['chroot', 'lxc', 'lxd', 'local', 'libvirt_qemu']
    PLAY_CA_CERT: "/usr/local/etc/ssl/cacert-curl.haxx.se.pem" # proxy?

    # These now come from the inventory except for connection = local,chroot in base_proxy.yml
    proxy_env:
      # hostvars[inventory_hostname]['http_proxy']
      http_proxy: "{{ http_proxy }}"
      https_proxy: "{{ https_proxy }}"
      socks_proxy: '{{ socks_proxy }}'
      ftp_proxy: '{{ ftp_proxy }}'
      no_proxy: '{{ no_proxy }}'
      SSL_CERT_FILE: "{{ SSL_CERT_FILE }}"
      RSYNC_PROXY: "{{ RSYNC_PROXY }}"

    # pass this in the -e extravars to the playbook command line - but you need the user and password too...
    CORP_NTLM_PROXY: ""

    # ...so put CORP_NTLM_PROXY with the username and password in the QeRcUser file
    # of the person running this playbook - not on the box - we use the RUN_ prefix.
    # If you dont want this, pass in RUN_QERC_USERFILE="" in the -e extra_vars on the command line
    # This is intened for credentials and could be vaulted - as opposed to runtime variables
    # stored in ~/.config/testforge/facts.d/testforge.yml
    RUN_QERC_USERFILE: "{{ lookup('env', 'HOME') }}/QeRcUser.yaml"

    # this should be set on the command line
    ROLES: []

    # pip uses /usr/local
    USR_LOCAL: "/usr/local"

    # we are installing into the prefix /var/local to not interfere with
    # other things that use /usr/local, including some things from other OSes.
    VAR_LOCAL: "/var/local"
    VAR_LOG: "{{VAR_LOCAL}}/var/log/testforge"

    PIP_CACHE: "/root/.cache/pip"
    # lynx uses SSL_CERT_DIR/SSL_CERT_FILE
    PIP_CA_CERT: "{{USR_LOCAL}}/etc/ssl/cacert-testserver.pem"
    PIP_INSTALL_ARGS: "--disable-pip-version-check --user --no-deps "

    # for localhost host operations with hostvms - eg hosts.yml
    PLAY_ANSIBLE_SRC: "{{ lookup('env', 'PWD')|default('') }}"
    PLAY_GI_DATA : /a/tmp/GentooImgr

  # lynis objects to . on the PATH and I cant find whos adding it
  # FixMe: does this change the PATH?
  environment:
    # NOT lookup('env', 'PATH')
    PATH: "{{ ansible_env.PATH  +':' +VAR_LOCAL +'/bin'|replace('.:', '')}}"

  pre_tasks:

    - block:

      - name: "Suspicious location (.) in PATH discovered"
        shell: |
          echo $PATH | grep '\.:' && echo "WARN: dot is on the PATH" && exit 1
          exit 0
        register: dot_on_path_fact
        # warning not an error - I cant see who is putting it on the PATH - a tailing :
        ignore_errors: true

      - name: lookup env PATH
        debug: msg="{{ ansible_env.PATH }}"
        when:
          - dot_on_path_fact is defined
          - dot_on_path_fact is failed

      - name: "set dates"
        set_fact:
          DOW: 0 # Day of week - unused
          DOM: "{{ ansible_date_time.day|int }}" # Day of month
          DATE: "{{ansible_date_time.day}}" # +%Y-%m-%d
          date_slash: "{{ ansible_date_time.date|replace('-','/') }}" # +%Y/%m/%d
          date_dash: "{{ ansible_date_time.date }}" # +%Y-%m-%d
          date_week_slash: "{{ ansible_date_time.year }}/{{ ansible_date_time.weeknumber }}"
          date_week_dash: "{{ ansible_date_time.year }}-{{ ansible_date_time.weeknumber }}"

      - debug:
          msg: "{{date_slash}} ansible_connection={{ansible_connection|default('') }} ROLES={{ROLES}}"

      - name: "hostvars[inventory_hostname]"
        debug:
          # |to_yaml
          msg: "hostvars[inventory_hostname] {{hostvars[inventory_hostname]}}"
        when: false

      - name: "ansible_lsb.id BOX_OS_FAMILY"
        assert:
          that:
            - "'{{ansible_lsb.id}}' == '{{BOX_OS_NAME}}'"
          success_msg: "BOX_OS_FAMILY={{BOX_OS_FAMILY}}"
          fail_msg: "ON tHE WRONG BOX {{ansible_lsb.id}} "
        when:
          - ansible_connection != 'local'
          - ansible_lsb.id|default('')" != ''
        ignore_errors: true

      - name: "check BOX_ANSIBLE_CONNECTIONS"
        assert:
          that:
            - "{{ansible_connection in BOX_ANSIBLE_CONNECTIONS}}"

      # required
      tags: always
      check_mode: false

    - block:

      - name: check nbd mounts
        shell: |
          cat /proc/partitions | grep nbd | head -1 | sed -e 's/.* //'
        changed_when: false
        register: nbd_out
        ignore_errors: true

      - name: nbd state
        debug:
          verbosity: 1
          msg: 'var={{nbd_out}} BOX_NBD_DEV={{BOX_NBD_DEV}}'
        ignore_errors: true

      - name: nbd fact no
        set_fact:
          nbd_disk: ""

      - name: nbd fact yes
        set_fact:
          nbd_dev: "{{nbd_out.stdout}}"
          nbd_disk: "/dev/{{nbd_out.stdout}}"
        when:
          - nbd_out.rc|default(1) == 0
          - nbd_out.stdout|default('') != ''

      # required
      tags: always
      check_mode: false
      when: ansible_connection == 'local' or  ansible_connection == 'chroot'

    - block:

      - name: "spinup libvirt hosts"
        shell: |
          sudo virsh net-list | grep -q default || \
              sudo virsh net-start default
          sudo virsh list | grep -q "{{ inventory_hostname }}" || \
              sudo virsh start "{{ inventory_hostname }}"
        delegate_to: localhost
        become: yes

      - name: "spinup libvirt hosts"
        # pip3.sh install ovirt-engine-sdk-python --break-system-packages
        ovirt:
          url: "qemu:///system"
          instance_name: ubuntu18.04
          instance_cpus: "1"
          state: started
          # instance_rootpw
          user: "{{ BOX_USER_NAME }}" #
          password: "{{ BOX_USER_NAME }}" # "{{ ansible_ssh_user }}
        become: yes
        #   msg: ovirtsdk required for this module
        ignore_errors: true

      # required
      tags: always
      check_mode: false
      when: ansible_connection == 'libvirt_qemu'

    - block:
        
      # after spinup
      - name: "we will use sudo and make it a prerequisite"
        shell: |
          [ -z "$TMPDIR" ] || [ -d "$TMPDIR" ] || mkdir -p "$TMPDIR"
          which sudo || exit 1
          # "check ansible_python_interpreter"
          "{{ansible_python_interpreter|default('python3')}}" --version

      # required
      tags: always
      check_mode: false

#    # required?
#    tags: always
#    check_mode: false

#  handlers:

  roles:
    # Always run the base prerequsite role.
    - role: base
      # When you use always: it breaks using daily/monthly/weekly tags - OK as base doesnt use them
      tags: always

    - role: proxy
      # You should run the proxy role even if you are not behind a proxy.
      tags: always
      when:
        - "'proxy' in ROLES"

#    - role: ansible-gentoo_install
#      when:
#        # BOX_OS_FAMILY == 'Gentoo' or BOX_GENTOO_FROM_MP != '' ?
#        - ( ansible_connection == 'local' and nbd_disk|default('') != '' ) or (ansible_connection == 'chroot' )

    - role: toxcore
      tags: always
      when:
        - "'toxcore' in ROLES"

  post_tasks:
    # queue up these at the end to leave a summary of what happened
    - block:

      - name: "ANSIBLE_RUN_LOG"
        shell: |
          ls -l "{{ ANSIBLE_RUN_LOG }}"
          exit 0
        register: grep_run_log
        ignore_errors: true

      - block:

        - name: last summary of WARN or ERROR in the logfile
          #debug: msg="{{ grep_run_log.stdout }}"
          #when: "grep_run_log is defined and grep_run_log.stdout_lines|length > 0"
          shell: |
            ANSIBLE_RUN_LOG="{{ ANSIBLE_RUN_LOG }}"
            [ -s "$ANSIBLE_RUN_LOG" ] || { echo "ERROR: empty $ANSIBLE_RUN_LOG" ; exit 2 ; }

            echo DEBUG: Summary for ROLES $roles
            echo DEBUG: WARN
            grep -h -e '^[ msg:-]*[W]ARN:' -e '^[ ]*.WARNING.:' \
              -e "^[' stderroumsg:-]*WARN:" $ANSIBLE_RUN_LOG

            echo DEBUG: ERROR
            grep -h -e '^[ msg:-]*[E]RROR:' -e 'Input/output error' \
              -e 'No such file or directory' -e '^[ ]*.ImportError:' \
              -e "^[' stderroumsg:-]*ERROR:" $ANSIBLE_RUN_LOG

            echo DEBUG: FAILED
            grep -h -e 'fatal: \|^failed: ' -B 1 $ANSIBLE_RUN_LOG
            exit 0

        when:
          - grep_run_log is success
        # required
        tags: always
        check_mode: false

      when:
        - ANSIBLE_RUN_LOG|default('') != ''
      delegate_to: localhost
      # required
      tags: always
      # Force a task to run in normal mode, even when the playbook is called with --check
      check_mode: false

# if .yamlint exists in this directory is ansible silently reading it?
# if it's garbage does it kill ansible with a no-descripted
# ERROR! Syntax Error while loading YAML.
