---

# When you configure Let's Encrypt certificate, sftpgo can't directly read the cert and key from /var/lib/dehydrated
# so a deploy_cert hook will copy them under {{ sftpgo_root_dir }}/etc/ssl
# But we still need to know the Let's Encrypt cert to use so the deploy hook will know which one to copy
# We do so by configuring certificate_file: letsencrypt:foo.example.org in SFTPGo configuration
- name: Handle Let's Encrypt cert
  set_fact:
    sftpgo_conf: "{{ sftpgo_conf | combine({ item: {'certificate_file': sftpgo_root_dir ~ '/etc/ssl/' ~ item ~ '.crt', 'certificate_key_file': sftpgo_root_dir ~ '/etc/ssl/' ~ item ~ '.key'}}, recursive=True) }}"
  loop:
    - ftpd
    - webdavd
    - httpd
    - telemetry
  when:
    - sftpgo_conf[item].certificate_file is defined
    - sftpgo_conf[item].certificate_file is search('^letsencrypt:')
  tags: sftpgo

- name: Deploy sftpgo config
  template: src=sftpgo.yml.j2 dest={{ sftpgo_root_dir }}/etc/sftpgo.yml group={{ sftpgo_user }} mode=640
  notify: restart sftpgo
  tags: sftpgo

- name: Generate self-signed certificate for ftpd
  import_tasks: ../includes/create_selfsigned_cert.yml
  vars:
    cert_path: "{{ sftpgo_root_dir }}/etc/ssl/ftpd.crt"
    cert_key_path: "{{ sftpgo_root_dir }}/etc/ssl/ftpd.key"
    cert_key_group: "{{ sftpgo_user }}"
    cert_key_mode: 640
  tags: sftpgo

- name: Generate self-signed certificate for webdavd
  import_tasks: ../includes/create_selfsigned_cert.yml
  vars:
    cert_path: "{{ sftpgo_root_dir }}/etc/ssl/webdavd.crt"
    cert_key_path: "{{ sftpgo_root_dir }}/etc/ssl/webdavd.key"
    cert_key_group: "{{ sftpgo_user }}"
    cert_key_mode: 640
  tags: sftpgo

- name: Generate self-signed certificate for httpd
  import_tasks: ../includes/create_selfsigned_cert.yml
  vars:
    cert_path: "{{ sftpgo_root_dir }}/etc/ssl/httpd.crt"
    cert_key_path: "{{ sftpgo_root_dir }}/etc/ssl/httpd.key"
    cert_key_group: "{{ sftpgo_user }}"
    cert_key_mode: 640
  tags: sftpgo

- name: Generate self-signed certificate for telemetry
  import_tasks: ../includes/create_selfsigned_cert.yml
  vars:
    cert_path: "{{ sftpgo_root_dir }}/etc/ssl/telemetry.crt"
    cert_key_path: "{{ sftpgo_root_dir }}/etc/ssl/telemetry.key"
    cert_key_group: "{{ sftpgo_user }}"
    cert_key_mode: 640
  tags: sftpgo

- name: Set permissions on certificates
  file: path={{ sftpgo_root_dir }}/etc/ssl/{{ item }}.crt owner=root group={{ sftpgo_user }} mode=644
  loop:
    - ftpd
    - webdavd
    - httpd
    - telemetry
  tags: sftpgo

- name: Set permissions on private keys
  file: path={{ sftpgo_root_dir }}/etc/ssl/{{ item }}.key owner=root group={{ sftpgo_user }} mode=640
  loop:
    - ftpd
    - webdavd
    - httpd
    - telemetry
  tags: sftpgo

- name: Init or upgrade the database
  command: "{{ sftpgo_root_dir }}/app/sftpgo --config-file {{ sftpgo_root_dir }}/etc/sftpgo.yml initprovider"
  become_user: "{{ sftpgo_user }}"
  when: sftpgo_install_mode != 'none'
  tags: sftpgo
