---
# creates the userdata from ansible datadir and deploy the signatures
# Attention: if USERLOGIN is defined:
#   Create signature only for the new user.
#   This prevents our employees from mass mailing.


- name: create signatures from datadir
  tags: create_signatures
  become: true
  become_user: perfact-useradmin
  when: ( 'perfact-login-' in  inventory_hostname )
  block:

    # copy script and templates:
    - name: copy script to target system
      ansible.builtin.template:
        src: templates/create_signatures.py
        dest: /opt/perfact/create_signatures/create_signatures.py
        mode: '0750'
        owner: perfact-useradmin

    - name: copy templates
      ansible.builtin.template:
        src: "templates/{{ item }}"
        dest: "/opt/perfact/create_signatures/{{ item }}"
        mode: '0640'
        owner: perfact-useradmin
      with_items:
        - signature_mail_text.html
        - signature_template_innovation_servicehotline.html
        - signature_template_evolution_servicehotline.html
        - signature_template_innovation_ostern.html
        - signature_template_evolution_ostern.html
        - signature_template_innovation_weihnachten.html
        - signature_template_evolution_weihnachten.html
        - signature_template_innovation_jubilaeum.html
        - signature_template_evolution_jubilaeum.html
        - signature_template_innovation_webinare.html
        - signature_template_evolution_webinare.html
        - signature_template_innovation_messe.html
        - signature_template_evolution_messe.html
        - signature_template_innovation_210331_industrial_pioneers.html
        - signature_template_evolution_210331_industrial_pioneers.html


    # this task creates the new data_source file based on the ansible datadir
    - name: generate data_source_users from ansible datadir
      ansible.builtin.template:
        src: data_source_users.py.j2
        dest: /opt/perfact/create_signatures/data_source_users.py

    # if USERLOGIN is undefined: Run for all users
    # ... and send mail to all user with 'signature_per_mail: True'.
    - name: rollout new signatures for all users
      ansible.builtin.command:
        cmd: sudo /opt/perfact/custom/perfact_useradmin.py create-signatures
        chdir: /opt/perfact/create_signatures/
      when: USERLOGIN is undefined

    # if USERLOGIN is defined: Run only for this user
    # ... and do not send mails to all other.
    - name: rollout new signatures for new user
      ansible.builtin.command:
        cmd: "sudo /opt/perfact/custom/perfact_useradmin.py create-signatures --user {{ USERLOGIN }}"
        chdir: /opt/perfact/create_signatures/
      when: USERLOGIN is defined
