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

---

- name: "toxcore main.yml"
  debug:
    verbosity: 1
    msg: "toxcore main.yml BOX_OS_FAMILY={{BOX_OS_FAMILY}} {{BOX_GENTOO_FROM_MP}} {{ansible_virtualization_role|replace('NA', 'host')}}"

- name: toxcore include_vars
  include_vars: "{{item}}.yml"
  with_items:
    - Linux
    - "{{ ansible_distribution }}{{ ansible_distribution_major_version }}"
  tags: always

- name: "rsync toxcore root_overlay"
  synchronize:
    src: "roles/toxcore/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 /var/local
  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 - tar before running
  unarchive:
    dest: /
    src: "{{item}}.tar"
    keep_newer: true
    owner: "{{BOX_ROOT_USER}}"
    # extra_opts: "{{ BASE_UNTAR_ARGS }}"
  with_items:
    - Linux
    - "{{ ansible_distribution }}"
  notify:
    - chmod /usr/local
  ignore_errors: true
  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: "make /var/local/var/log/testforge toxcore"
  file:
    path: "{{ item }}"
    state: directory
    mode: 0775
  with_items:
    - "{{ TOXCORE_LOG_DIR }}"
    - "{{ TOXCORE_DAILY_LOG }}"
#    - "{{ TOXCORE_WEEKLY_LOG }}"
#    - "{{ TOXCORE_MONTHLY_LOG }}"
  tags:
    - hourly
    - daily
    - weekly
    - monthly

- name: "/var/local/bin/toxcore_sign_modules.bash modules needed toxcore_kmods_in_host"
  shell: |
    KVER=`cat /proc/cmdline |sed -e 's/ .*//' -e 's/BOOT_IMAGE=//' -e 's/kernel-[a-z]*-x86_64-//'`
    KDIR=/lib/modules/$KVER
    DIR=$KDIR/misc
    [ -d $DIR ] || { echo WARN: no directory $DIR ; exit 0 ; }
    /var/local/bin/toxcore_sign_modules.bash {{ toxcore_kmods_in_host|flatten|join(' ') }}

  when: false
  # this changes with kernel 4 -> 5

- name: modprobe VM modules toxcore_kmods_in_host
  modprobe:
    name: "{{ item }}"
    # "{{ 'absent' if ansible_virtualization_role|replace('NA', 'host') != 'host' else 'present'}}"
    state: present
  when:
    - item != ''
  with_items: "{{ toxcore_kmods_in_host }}"
  ignore_errors: true

- name: modprobe VM modules toxcore_kmods_not_in_host
  modprobe:
    name: "{{ item }}"
    state: absent
  with_items: "{{ toxcore_kmods_not_in_host }}"
  when: false
  # I'm not sure kvm should be missing anymore 5+
  ignore_errors: true

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

- name: add standard_users to groups
  user:
    name: "{{ item.0 }}"
    append: true
    groups: "{{ item.1 }}"
  when:
    - item != ''
    - "len(toxcore_system_users) > 0"
  # some groups may not be there
  ignore_errors: true
  with_nested:
    -
      - "{{ toxcore_system_users }}"
    -
      - "{{ toxcore_standard_users_groups_host if ansible_virtualization_role|replace('NA', 'host') == 'host' else [] }}"
      - "{{ toxcore_standard_users_groups_guest if ansible_virtualization_role|replace('NA', 'host') != 'host' else [] }}"

- name: "make a directory for /data/Vms"
  file:
    path: "{{item }}"
    state: directory
    mode: 0775
  with_items:
    - "{{TOXCORE_VMS_DIR}}"
    - "{{TOXCORE_VMS_DIR}}/Instances"
    - "{{TOXCORE_VMS_DIR}}/Qemu"
    - "{{TOXCORE_VMS_DIR}}/Boxes"
#?    - "{{TOXCORE_VMS_DIR}}/vagrant.d/tmp"
  check_mode: false

- name: "toxcore gpg keys system"
  # Option --keyserver must be used to
  environment: "{{ shell_proxy_env }}"
  shell: |
    /usr/bin/gpg --list-keys | grep "{{ item.primary }}" || \
      /usr/bin/gpg --recv-keys "{{ item.uid }}" # --keyserver "{{ TOXCORE_GPG_SERVER }}"
  with_items: "{{ toxcore_gpg_keys_system }}"
  when:
    - toxcore_gpg_keys_system|length > 0
    - BASE_ARE_CONNECTED|default('') != ''
    - false # none yet
  ignore_errors: true

- name: "toxcore gpg keys gentoo"
  environment: "{{ shell_proxy_env }}"
  shell: |
    [ -f /usr/share/openpgp-keys/gentoo-release.asc ] && exit 0
    gpg --import /usr/local/share/openpgp-keys/gentoo-release.asc

# FixMe: does this do SSH?
- name: /usr/local/bin/gitproxy.sh
  blockinfile:
    dest: "/usr/local/bin/gitproxy.bash"
    create: yes
    mode: 0775
    marker: "# {mark} ANSIBLE MANAGED BLOCK proxy"
    block: |
      exec corkscrew {{HTTP_PROXYHOST}} {{HTTP_PROXYPORT}} $1 $2
      # $1 %h $2 %p
      #? exec connect -4 -S {{HTTP_PROXYHOST}}:{{HTTP_PROXYPORT}} $(tor-resolve $1 {{HTTP_PROXYHOST}}:{{HTTP_PROXYPORT}}) $2

# this should not run as root
# delegate_to: localhost? - no - per test
- name: "usr_local_toxcore.bash"
  environment: "{{ shell_proxy_env }}"
  shell: |
    umask 0002
    sudo -u  "{{ BOX_USER_NAME }}" \
    bash {{TOXCORE_USR_LOCAL}}/src/usr_local_toxcore.bash \
              {{ 'check' if ansible_check_mode }}
    exit 0
  args:
    chdir: "{{TOXCORE_USR_LOCAL}}/src"
  ignore_errors: true
  check_mode: false

- name: "include_tasks toxcore vms as root"
  include_tasks:
    file: "{{LOOP_ITEM}}.yml"
    apply:
      environment: "{{ proxy_env }}"
  when:
    - LOOP_ITEM  != '' and LOOP_ITEM  != []
  with_items:
    - "vms"
    - "{{ 'libvirt' if (BOX_WHONIX_PROXY_HOST != '' or 'libvirt' in BOX_TOXCORE_FEATURES or 'whonix' in BOX_TOXCORE_FEATURES) else [] }}"
  loop_control:
    loop_var: LOOP_ITEM

    
- name: install toxcore pips HOST
  environment: "{{ portage_proxy_env }}"
  shell:  |
    sudo -u  "{{ BOX_USER_NAME }}" \
    pip3.sh install {{' '.join(toxcore_pips3_inst_host if ansible_virtualization_role|replace('NA', 'host') == 'host' else toxcore_pips3_inst_guest)}}
  ignore_errors: "{{ BASE_PKG_IGNORE_ERRORS }}"
  when:
    - BASE_ARE_CONNECTED|default('') != ''
    - "ansible_virtualization_role|replace('NA', 'host') == 'host'"
    - "len(toxcore_pips3_inst) > 0"

- name: install toxcore pips GUEST
  environment: "{{ portage_proxy_env }}"
  shell:  |
    [ -z "{{' '.join(toxcore_pips3_inst_guest)}}" ] || \
        sudo -u  "{{ BOX_USER_NAME }}" \
        pip3.sh install {{' '.join(toxcore_pips3_inst_guest)}}
  ignore_errors: "{{ BASE_PKG_IGNORE_ERRORS }}"
  when:
    - BASE_ARE_CONNECTED|default('') != ''
    - "ansible_virtualization_role|replace('NA', 'host') != 'host'"

- name: "include_tasks toxcore users as user"
  include_tasks:
    file: "{{ LOOP_USER_F[1] }}.yml"
    apply:
      environment: "{{ proxy_env }}"
      become_user: "{{ LOOP_USER_F[0] }}"
  when:
    - "LOOP_USER_F[1] != ''"
    - "ansible_virtualization_role|replace('NA', 'host') == 'host'"
    - false
  with_nested:
    -
#no      - users
      - "{{ 'libvirt_users' if 'libvirt' in TOXCORE_FEATURES else '' }}"
#      - "{{ 'qemu_users' if 'qemu' in TOXCORE_FEATURES else '' }}"
#      - "{{ 'docker_users' if 'docker' in TOXCORE_FEATURES else '' }}"
  loop_control:
    loop_var: LOOP_USER_F

- name: enable and start toxcore services
  service:
    name: "{{ item }}"
    enabled: yes
    state: started
  when:
    - "item != ''"
    - ansible_connection|default('') not in PLAY_CHROOT_CONNECTIONS
  with_items: "{{ toxcore_services_enabled_host if ansible_virtualization_role|replace('NA', 'host') == 'host' else toxcore_services_enabled_guest }}"
  ignore_errors: true

- name: start toxcore services
  service:
    name: "{{ item }}"
    enabled: no
    state: started
  when:
    - "item != ''"
    - ansible_connection|default('') not in PLAY_CHROOT_CONNECTIONS
    - false
  with_items: "{{ toxcore_services_started }}"
  ignore_errors: true

- name: stop toxcore services
  service:
    name: "{{ item }}"
    enabled: no
    state: stopped
  failed_when: false
  when:
    - "item != ''"
    - ansible_connection|default('') not in PLAY_CHROOT_CONNECTIONS
    - false
  with_items: "{{ toxcore_services_stopped }}"

- name: run ansible-gentoo_install
  include_role:
    name: ansible-gentoo_install
  when:
    - "ansible_virtualization_role|replace('NA', 'host') == 'host'"
#    - BOX_OS_FAMILY == 'Gentoo' or BOX_GENTOO_FROM_MP not in ['/', '']

  # Set BOX_NBD_OVERLAY_DIR environment variable to override storage location for VMs
  #   -b      Bridge interface to use (defaults to virbr0)
  #   -m      MAC address to use (default is to use a randomly-generated MAC)
  #   -p      ansible users plaintext password
  #   -k      Full path and name of the ansible user's public key file (required)

- name: run toxcore_create-vm.bash
  delegate_to: localhost
  shell: |
    export BOX_NBD_OVERLAY_DIR=${BOX_NBD_OVERLAY_DIR:-"${HOME}/vms/virsh"}
    [ '{{BOX_NBD_OVERLAY_NAME}}' != '' ] || exit 1
    [ '{{BOX_NBD_OVERLAY_DIR}}' != '' ] || exit 2
    [ '{{BOX_NBD_BASE_PUBKEY}}' != '' ] || exit 3
    [ '{{BOX_NBD_BASE_QCOW}}' != '' ] || exit 4
    [ '{{BOX_NBD_OVERLAY_RAM}}' != '' ] || exit 5
    [ '{{BOX_NBD_OVERLAY_BR}}' != '' ] || exit 6
    [ '{{BOX_NBD_OVERLAY_GB}}' != '' ] || exit 7
    [ '{{BOX_NBD_OVERLAY_CPUS}}' != '' ] || exit 8
    [ '{{BOX_NBD_OVERLAY_PASS}}' != '' ] || exit 9
    if [ ! -f '{{BOX_NBD_BASE_QCOW}}' ] ; then
        echo WARN: '{{BOX_NBD_BASE_QCOW}}' not built yet - skipping
        exit 0
    fi
    if [ -z '{{BOX_NBD_BASE_PASS}}' ] ; then
        echo WARN: 'BOX_NBD_BASE_PASS' empty
        exit 10
    fi
    toxcore_create-vm.bash \
             -n {{BOX_NBD_OVERLAY_NAME}} \
             -k {{BOX_NBD_BASE_PUBKEY}} \
             -i {{BOX_NBD_BASE_QCOW}} \
             -s {{BOX_NBD_OVERLAY_GB}} \
             -c {{BOX_NBD_OVERLAY_CPUS}} \
             -r {{BOX_NBD_OVERLAY_RAM}} \
             -d {{BOX_NBD_OVERLAY_DIR}} \
             -b {{BOX_NBD_OVERLAY_BR}}  \
             -p {{BOX_NBD_OVERLAY_PASS}} \
             -o gentoo
  args:
    creates: "{{BOX_NBD_OVERLAY_DIR}}/{{BOX_NBD_OVERLAY_NAME}}.qcow2"
  ignore_errors: true
  when:
    - "ansible_virtualization_role|replace('NA', 'host') == 'host'"

# run this last

# works with apply tags hourly
- name: toxcore hourly include_tasks
  include_tasks:
    file: "hourly.yml"
    apply:
      tags:
        - always
  with_items:
    - "{{ toxcore_system_users }}"
  loop_control:
    loop_var: LOOP_USER
  tags:
    - always

- name: toxcore daily include_tasks
  include_tasks:
    file: "daily.yml"
    apply:
      environment: "{{ proxy_env }}"
      tags:
        - daily
  tags:
    - daily

- name: toxcore weekly include_tasks
  include_tasks:
    file: "weekly.yml"
    apply:
      environment: "{{ proxy_env }}"
      tags:
        - weekly
  tags:
    - weekly
  when: false


# replace this ^A with a control-A to provoke an error in the error handler of yamlint
# yaml.reader.ReaderError: unacceptable character #x0001: special characters are not allowed

- block:
    
    - name: ansible-keepassxc
      ansible-keepassxc:
        database: "{{ base_passwords_database }}"
        entry: "TOXCORE_LXD_TRUST_PASSWORD"
        group: "/Ansible/toxcore"
        password: "{{ base_passwords_password }}"
      no_log: False
      register:  toxcore_lxd_trust_password

    - debug:
        verbosity: 1
        var: toxcore_lxd_trust_password

  check_mode: false
  rescue:
    - debug:
        verbosity: 1
        msg: "toxcore vms.yml WARN RESCUE undefined or missing base_passwords_database "
          
    - set_fact:
        base_passwords_password: "{{TOXCORE_LXD_TRUST_PASSWORD}}"
  when: false
