---
# setup user on perfact-login in ldap and homedir and create ssh-key

# user must be created in ldap on perfact-login first
- name: perfact_adduser - ldap_add_user
  # tags are configured in role
  tags: always
  ansible.builtin.include_role: name=internalit/roles/perfact_adduser/ldap_add_user

- name: Pause for 2 seconds to allow to sync new user to ldap pam
  ansible.builtin.pause:
    seconds: 2

# the homedir on perfact-login was already created by
#   perfact-useradmin.py file-create-user

- name: create files in homedir
  tags: always
  become: true
  become_user: perfact-useradmin
  block:
  - name: check presense of id_rsa on perfact-login
    tags: create_sshkey
    ansible.builtin.command: "sudo /opt/perfact/custom/perfact_useradmin.py file-sshkey-show --user {{ USERLOGIN }}"
    # run also in check_mode
    check_mode: false
    ignore_errors: true
    # dont show error
    no_log: true
    register: id_rsa_present_on_perfact_login

  - name: set tigged_secret_ssh_key
    set_fact:
      tigged_secret_ssh_key: "{{ secret_ssh_key }}"
    diff: false
    check_mode: false
    when: id_rsa_present_on_perfact_login.failed

  - name: Create a 4096-bit SSH key for user in homedir .ssh/id_rsa
    tags: create_sshkey
    ansible.builtin.command: "sudo /opt/perfact/custom/perfact_useradmin.py file-sshkey-create --user {{ USERLOGIN }} --password {{ tigged_secret_ssh_key }} --comment {{ users[USERLOGIN].mail_address }}"
    when: id_rsa_present_on_perfact_login.failed

  # TODO: get pubkey from perfact-login-prod and store in datadir
  # This is done in laptop installation, but would be much nicer here, direct
  # after creating the key.

  - name: create signature for new user
    tags: create_signatures
    # creates the userdata from ansible datadir and deploy the signatures
    # (if USERLOGIN is defined: create signature only for the new user and
    # do not send mail to everyone)
    ansible.builtin.include_role:
      name=internalit/roles/perfact-login/create_signatures

  - name: create pf_verbindungskonfiguration for new user
    tags: pf_verbindungskonfiguration
    ansible.builtin.command: "sudo /opt/perfact/custom/perfact_useradmin.py renew-pf-verbindungskonfiguration"
