---
- name: Check if FTP account exist
  command: grep "^{{ item.name }}:" /etc/proftpd/vpasswd
  failed_when: false
  check_mode: no
  changed_when: check_ftp_account.rc != 0
  register: check_ftp_account

- block:

  - name: Get current FTP password
    shell: grep "^{{ item.name }}:" /etc/proftpd/vpasswd | cut -d':' -f2
    register: protftpd_cur_password
    check_mode: no
    changed_when: false

  - name: Set password for this account
    set_fact:
      protftpd_password: "{{ protftpd_cur_password.stdout }}"

  when: check_ftp_account.rc == 0

- block:

  - name: Generate FTP password
    command: "apg -n 1 -m 16 -M lcN"
    register: proftpd_apg_password
    check_mode: no

  - name: Print generated password
    debug:
      msg: "{{ proftpd_apg_password.stdout }}"

  - name: Hash generated password
    set_fact:
      protftpd_password: "{{ proftpd_apg_password.stdout | password_hash('sha512') }}"

  when: check_ftp_account.rc != 0

- name: Update proftpd_accounts with password
  set_fact:
    proftpd_accounts_final: "{{ proftpd_accounts_final + [ item | combine({ 'password': protftpd_password }) ] }}"
