---
# roles/perfact_adduser/tasks/main.yml


# parameters ---extra-vars "USERLOGIN=.... USERLAPTOPIP=...."

- name: userlaptop_install exit if USERLOGIN is not given on commandline check in install
  ansible.builtin.fail:
    msg: "Error: USERLOGIN is not given on commandline"
  when: USERLOGIN is undefined
  check_mode: false

# run this tasks on userlatop - only if  USERLAPTOPIP is given on commandline
- when: inventory_hostname == "userlaptop"  and USERLAPTOPIP is defined
  block:

    ################################
    #####   install software   #####
    ################################
    # gather fact required by intall programms and role 'perfact_repo'
    - name: userlaptop_install gather facts from userlaptop now
      ansible.builtin.setup:
        filter:
          - 'ansible_distribution_release'
          - 'ansible_distribution'

    - name: install programms on Debian laptop
      become: true
      ansible.builtin.apt:
        name:
          # required on fresh laptop:
          - sshpass
          # tools
          - vim
          # userspace programms:
          - thunderbird
          #- thunderbird-locale-de
          - libreoffice
          - libreoffice-l10n-de
          - libreoffice-gnome
          #- libreoffice-style-yaru
          - libreoffice-gtk3
          #- language-pack-de
          # perfact-olpg wants:
          - aspell
          - aspell-en
          - aspell-de
          - fonts-liberation
          - flameshot
          - iftop
          - iotop
          - lshw
          - tcpdump
          - lynx
          - tig
          - git
          - gitk
          - obs-studio
          - flowblade
          - screenkey
          - openvpn
          - policykit-1
          - python3-sphinx
          - python3-sphinx-rtd-theme
          - pandoc
          - latexmk
          - python3-all
          - flake8
          - python3-autopep8
          - tox
          - python3-dev
          - qemu-user-static
          - qemu-system-arm
          - mosquitto-clients
          - python3-virtualenv
          - devscripts
          - unixodbc-dev
          - debhelper
          - dh-python
        state: present
        install_recommends: false
        update_cache: true
      when: ansible_distribution == 'Debian'

    # install on ubuntu:
    - name: install programms on Ubuntu laptop
      become: true
      ansible.builtin.apt:
        name:
          # required on fresh laptop:
          - sshpass
          # tools
          - vim
          # userspace programms:
          - thunderbird
          - thunderbird-locale-de
          - libreoffice
          - libreoffice-l10n-de
          - libreoffice-gnome
          - libreoffice-style-yaru
          - libreoffice-gtk3
          - language-pack-de
        state: present
        install_recommends: false
        update_cache: true
      when: ansible_distribution == 'Ubuntu'

    ##############################################
    #####   install perfact-olpg on laptop   #####
    ##############################################
    - name: check if olpg was installed
      # check presence of /usr/bin/perfact-connect
      ansible.builtin.stat:
        path: "/usr/bin/perfact-connect"
      register: file_olpg_exists

    - debug:
        var: file_olpg_exists

    - name: install procedure for perfact-olpg
      when: file_olpg_exists.stat.exists == false
      block:
      - name: userlaptop_install add perfact-repo to userlaptop
        include_role:
          name: ../roles/general/perfact-repo

      - name: remove file flag signaling end of atjob from perfact-olpg
        become: true
        ansible.builtin.file:
          path: /var/run/perfact-olpg-atjob-finished
          state: absent
        ignore_errors: true
        no_log: true

      # use nmu version - other breaks wiht OpenSSL in perfact-connect
      # TODO: reactivate install of normal package
      - name: download nmu version
        ansible.builtin.get_url:
          url: https://cloud.perfact.de/index.php/s/nr2Y5fFA7AEszLH/download?path=%2Fbookworm%2Fpackages&files=perfact-olpg_1.2.20%2Bnmu2_amd64.deb
          dest: /tmp/perfact-olpg_1.2.20_nmu2_amd64.deb

      - name: install from file
        become: true
        ansible.builtin.apt: deb=/tmp/perfact-olpg_1.2.20_nmu2_amd64.deb

  #    # install perfact-olpg from repositoy
  #    - name: userlaptop_install install perfact-olpg
  #      become: true
  #      ansible.builtin.apt:
  #        name: perfact-olpg
  #        state: present
  #        install_recommends: false

      # by installing perfact-olpg first, we need to wait for background atjob
      # to finish
      - name: wait for atjob fron perfact-olpg before continuing
        ansible.builtin.wait_for:
          path: /var/run/perfact-olpg-atjob-finished
          # wait maximal 4 minutes
          timeout: 240
          # ignore error because atjob is not reliable in terminating
        ignore_errors: true
      # TODO: error handling or at least log in this atjob

    ###################################################
    #####      prepare for login                  #####
    #####      unattended 'perfact-storepass'     #####
    ###################################################

    - name: create dir ~/.config/perfact-olpg
      # this is what /usr/bin/perfact-olpg-config does:
      ansible.builtin.file:
        path: "/home/{{ Laptop_User }}/.config/perfact-olpg"
        state: directory
        mode: '0755'

    - name: create ~/.config/perfact-olpg/conf.sh
      # this is what /usr/bin/perfact-olpg-config does:
      ansible.builtin.copy:
        content: |
          # This configuration is sourced by the perfact-olpg utilities. Use bash syntax.
          #
          # Username at PerFact
          perfactuser={{ USERLOGIN }}
        dest: "/home/{{ Laptop_User }}/.config/perfact-olpg/conf.sh"

    - name: copy initial ssh_config from olpg package
      # this is what perfact-storepass does:
      ansible.builtin.copy:
        src: /usr/share/perfact/olpg/connect/ssh_config_init_template
        remote_src: true
        dest: "/home/{{ Laptop_User }}/.ssh/ssh_config_init"
        mode: '0644'

    - name: replace username in ssh_config
      # this is what perfact-storepass does:
      ansible.builtin.replace:
        path: "/home/{{ Laptop_User }}/.ssh/ssh_config_init"
        regexp: "{user}"
        replace: "{{ USERLOGIN }}"

    # TODO:  extend perfat-storepass with parameter for unattended setup
    # (now theses tasks have been programmed twice)

    # FIXME:  storing passwords it not possible before the laptop is rebooted

    ###########################################
    #####   store passwords in keystore   #####
    ###########################################
    # - name: debug vars from userpass
    #   debug:
    #     var: local_ssh_key
    # OK  variable is availible

    ## next try by adding gnome-keyring to the iso
    ## hope it is availible from frist login
    #    # FIXME: programm scret-tool "hangs" after typing the password
    #    # A reboot solved this issue.
    #    # I do not wat to reboot now
    #    # kill the gnmoe-keyring-daemon
    #    - name: kill gnome-keyring-daemon
    #      ansible.builtin.command: killall gnome-keyring-daemon
    #      ignore_errors: true
    #      no_log: true
    # this did not help. Try to unlock...
    #
    #   # unlock the keyring with userpassword as login would have done:
    #   - name: unlock gnome-keyring-daemon with user pass like at logon
    #     ansible.builtin.shell: "echo -n '{{ Laptop_Userpassword }}' | gnome-keyring-daemon -l"
    #   # Geht nicht. Es gibt Hinweise, dass DEbain an anderes Paswort zum
    #   # Entsperren nimmt.

    # unable to resolve this in a reasonable time.
    # Going to logoff and logon the user - that did not help ...


    # das einzige was hier aktuell hilft ist ein Reboot!

    # Status:
    # Vor dem Reboot läuft:
    #  19847  0.1  0.0 240432 10612 ?   Sl   16:56   0:00 /usr/bin/gnome-keyring-daemon --daemonize --login
    #  19893  0.1  0.0 240288 12052 ?   Ssl  16:56   0:00 /usr/bin/gnome-keyring-daemon --foreground --components=pkcs11,secrets --control-directory=/run/user/1000/keyring
    #
    # Nach dem Reboot läuft nur ein Prozess:
    #  2128   0.1  0.0 240324 11984 ?   SLsl 17:07   0:00 /usr/bin/gnome-keyring-daemon --foreground --components=pkcs11,secrets --control-directory=/run/user/1000/keyring
    #
    # Update:
    # auf einem anderen Laptop läuft aber nur der zweite keyring-Prozess und es
    # geht trotzdem nicht ohne reboot.

    - name: hint to reboot if tasks hangs
      debug:
        msg: Wenn folgender Tasks nicht weiter läuft, hilft ein Reboot, um den Keystore zu erreichen.

    - name: store password in keystore for No 1 phonehome-key
      ansible.builtin.shell: |
        secret-tool store \
        --label="Unlock password for: {{ USERLOGIN }}${HOSTNAME}_perfact_phonehome" \
        unique \
        "ssh-store:${HOME}/.ssh/id_rsa_perfact_phonehome"
      args:
        stdin: "{{ local_ssh_key }}"
        stdin_add_newline: false
      # hide passwords:
      diff: false

    # 2. id_rsa_perfact-file
    # secret-tool store --label="Unlock password for: USER@${HOSTNAME}_perfact-file" \
    #      unique ssh-store:${HOME}/.ssh/id_rsa_perfact-file
    - name: store password in keystore for No 2 pfile
      ansible.builtin.shell: |
        secret-tool store \
        --label="Unlock password for: {{ USERLOGIN }}${HOSTNAME}_perfact_file" \
        unique \
        "ssh-store:${HOME}/.ssh/id_rsa_perfact_file"
      args:
        stdin: "{{ pffile_ssh_key }}"
        stdin_add_newline: false
      # hide passwords:
      diff: false

    # 3. ssh-key on perfact-file
    # secret-tool store --label="PerFact Connect SSH Key" \
    #    perfact-connect ssh-passphrase
    - name: store password in keystore for No 3 ssh key from pffile
      ansible.builtin.shell: |
        secret-tool store \
        --label="PerFact Connect SSH Key" \
        perfact-connect ssh-passphrase
      args:
        stdin: "{{ secret_ssh_key }}"
        stdin_add_newline: false
      # hide passwords:
      diff: false

    ##############################################
    #####   ssh-key setup for perfact-olpg   #####
    ##############################################
    ###
    ###     key for login to pf-phonehome
    ###

    # 1. check if key for phonehome exists
    - name: userlaptop_install check presence of ssh-key for phonehome
      ansible.builtin.command: ls -l  ~/.ssh/id_rsa_perfact_phonehome
      ignore_errors: true
      register: phonehome_key_present
      # do not print the big red error
      no_log: true

    # 2. create key if not exists for phonehome
    - name: userlaptop_install create ssh-key for phonehome
      ansible.builtin.command: ssh-keygen -t rsa -b 4096 -C "{{ USERLOGIN }}@laptop-{{ USERLOGIN }}_phonehome_key" -N "{{ local_ssh_key }}" -f ~/.ssh/id_rsa_perfact_phonehome
      when: phonehome_key_present.rc  != 0
      # do not log passwords
      diff: false

    # 3. ouput pubkey and store in var
    - name: userlaptop_install get pubic key for phonehome
      ansible.builtin.command: cat  ~/.ssh/id_rsa_perfact_phonehome.pub
      register: phonehome_key_pub

    ## 3a. debug var
    #- name: userlaptop_install debug phonehome_key_pub
    #  debug:
    #    var: phonehome_key_pub.stdout


    ###
    ###     key for login to perfact-login-prod
    ###

    # Hint:
    # the name of this key is still 'perfact_file' (from previous pffile)

    # check if key for pffile exists
    - name: userlaptop_install check presence of ssh-key for pffile
      ansible.builtin.command: ls -l  ~/.ssh/id_rsa_perfact_file
      ignore_errors: true
      # do not print the big red error
      no_log: true
      register: pffile_key_present

    # create key if not exists
    - name: userlaptop_install create ssh-key for pffile
      ansible.builtin.command: ssh-keygen -t rsa -b 4096 -C "{{ USERLOGIN }}@laptop-{{ USERLOGIN }}_pffile_key" -N "{{ pffile_ssh_key }}" -f ~/.ssh/id_rsa_perfact_file
      when: pffile_key_present.rc  != 0
      # do not log passwords
      diff: false

    # ouput pubkey and store in var
    - name: userlaptop_install get pubic key for pffile
      ansible.builtin.command: cat  ~/.ssh/id_rsa_perfact_file.pub
      register: pffile_key_pub

    #- name: userlaptop_install debug pffile_key_pub
    #  debug:
    #    var: pffile_key_pub.stdout

    # put public key to perfact-login-prod
    # user and homedir and ~/.ssh/ have already been created
    # become root is not possible on restricted production system
    # we have to login with password to store the key
    - name: set tigged_pffile_passwd to be used for shell-scripts later
      set_fact:
        tigged_pffile_passwd: "'{{ pffile_passwd }}'"
      diff: false
      check_mode: false

    - name: add hostkey and allow login without password on perfact-login-prod
      # execute on laptop:
      # this "hangs" at verification of the encrypted key while waiting for
      # the key passphase in the background.
      # Warkoround: We are unsing -f not to verify the presense of the key.
      # This will add the key every time the task runs.
      # ==>> TODO: we like to have a working keystore here...
      ansible.builtin.command: "/usr/bin/sshpass -p {{ tigged_pffile_passwd }} /usr/bin/ssh-copy-id -f -o StrictHostKeyChecking=accept-new -o PreferredAuthentications=password -i ~/.ssh/id_rsa_perfact_file perfact-login-prod.perfact.de"
      # do not log passwords
      diff: false

    - name: add hostkey and allow login without password on perfact-file-prod
      # execute on laptop:
      # the homedir will be create on first login by ldap-pam
      #
      # this "hangs" at verification of the encrypted key while waiting for
      # the key passphase in the background.
      # Warkoround: We are unsing -f not to verify the presense of the key.
      # This will add the key every time the task runs.
      # ==>> TODO: we like to have a working keystore here...
      ansible.builtin.command: "/usr/bin/sshpass -p {{ tigged_pffile_passwd }} /usr/bin/ssh-copy-id -f -o StrictHostKeyChecking=accept-new -o PreferredAuthentications=password -i ~/.ssh/id_rsa_perfact_file perfact-file-prod.perfact.de"
      # do not log passwords
      diff: false
      # FIXME: this tasks failes. the tasks before not:
      # fatal: [userlaptop]: FAILED! => {"changed": true, "cmd":
      # ["/usr/bin/sshpass", "-p", "SECRETPASS", "/usr/bin/ssh-copy-id", "-o",
      # "StrictHostKeyChecking=accept-new", "-o", "PreferredAuthentications=password",
      #  "-i", "~/.ssh/id_rsa_perfact_file", "perfact-file-prod.perfact.de"],
      #  "delta": "0:00:00.452574", "end": "2023-11-27 18:38:00.293901",
      #  "msg": "non-zero return code", "rc": 1, ...
      # "stderr": "/usr/bin/ssh-copy-id: INFO: Source of key(s) to be
      # installed: \"/home/mwascher/.ssh/id_rsa_perfact_file.pub\"\n
      # /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s),
      #  to filter out any that are already installed\n
      # /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if
      # you are prompted now it is to install the new keys\n
      # mwascher@perfact-file-prod.perfact.de: Permission denied (publickey).",
      # "stderr_lines": ["/usr/bin/ssh-copy-id: INFO: Source of key(s) to be
      # installed: \"/home/mwascher/.ssh/id_rsa_perfact_file.pub\"",
      # "/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s),
      # to filter out any that are already installed", "/usr/bin/ssh-copy-id:
      # INFO: 1 key(s) remain to be installed -- if you are prompted now it
      # is to install the new keys", "mwascher@perfact-file-prod.perfact.de:
      # Permission denied (publickey)."], "stdout": "", "stdout_lines": []}
      #
      # Difference: at least: the homedir does not exists


    # Hint:
    # The private key for ssh-access stored on perfact-login was created
    # by role/perfact_adduser/perfact-login before
    #
    # now we get the public key for storing into datadir/user

    - name: userlaptop_install get pffile_secret_key_pub from perfact-login-prod
      # become on restricted production system ist not possible
      # instead: login with user from laptop and print content of file:
      ansible.builtin.command: "/usr/bin/sshpass -p {{ tigged_pffile_passwd }} ssh -o PreferredAuthentications=password perfact-login-prod.perfact.de cat /home/{{ USERLOGIN }}/.ssh/id_rsa.pub"
      register: pffile_secret_key_pub

    - name: userlaptop_install debug pffile_secret_key_pub
      debug:
        var: pffile_secret_key_pub.stdout

    ####################################################
    #####   copy pubkeys to data/users/USERLOGIN   #####
    ####################################################
    - name: userlaptop_install append ssh public keys to data/user/...
      local_action:
        module: blockinfile
        path: "./data/users/{{ USERLOGIN }}"
        marker: "# {mark} by Ansible by playbook_perfact_aduser / userlaptop_install"
        block: |
          ssh_keys:
            pffile: {{ pffile_secret_key_pub.stdout }}
            laptop:
              - {{ phonehome_key_pub.stdout }}

    ####################################################
    #####   create user @ pf-phonehome-2020-prod   #####
    ####################################################

    # It is planned to transfer pf-phonehome to a restricted production system.
    # TODO: become root is then no longer possible
    #       better change this tasks before go live

    - name: check if user already exists on pf-phonehome-2020-prod
      become: true
      ansible.builtin.command: "getent passwd {{ USERLOGIN }}"
      register: pf_phonehome_user_present
      ignore_errors: true
      delegate_to: pf-phonehome-2020-prod

    - name: create this user of pf-phonehome-2020-prod
      when: pf_phonehome_user_present.rc != 0
      become: true
      user:
        name: "{{ USERLOGIN }}"
        groups: perfact_employees
      delegate_to: pf-phonehome-2020-prod

    - name: add no_pty to ssh-key
      set_fact:
        phonehome_key_no_pty: "no-pty {{ phonehome_key_pub.stdout }}"

    - name: create authorized_key for this user on pf-phonehome-2020-prod
      become: true
      authorized_key:
        user: "{{ USERLOGIN }}"
        key: "{{ phonehome_key_no_pty }}"
        exclusive: true
      delegate_to: pf-phonehome-2020-prod



    # add Git variables
    - name: userlaptop_install add git variables
      ansible.builtin.blockinfile:
        path: ~/.profile
        insertafter: EOF
        block: |
                # PerFact settings to forward GIT variables via SSH"
                export GIT_AUTHOR_NAME="{{ users[USERLOGIN].full_name }}"
                export GIT_AUTHOR_EMAIL="{{ users[USERLOGIN].mail_address }}"
                export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"
                export GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"

    # optional but very nice:
    #   add account data to thunderbird
    #   confiure autostart on laptop
    # optinal but very nice:
    #   configure user account on ema including cert
    #   extract psafe and copy to perfact-login (now pffile)
