---

- name: Enable index.html creation if user doesn't wish to customise base domain
  delegate_to: 127.0.0.1
  lineinfile:
    path: '{{ awx_cached_matrix_vars }}'
    regexp: "^#? *{{ item.key | regex_escape() }}:"
    line: "{{ item.key }}: {{ item.value }}"
    insertafter: '# Base Domain Settings Start'
  with_dict:
    'matrix_nginx_proxy_base_domain_homepage_enabled': 'true'
  when: (awx_customise_base_domain_website is defined) and not awx_customise_base_domain_website|bool

- name: Disable index.html creation to allow multi-file site if user does wish to customise base domain
  delegate_to: 127.0.0.1
  lineinfile:
    path: '{{ awx_cached_matrix_vars }}'
    regexp: "^#? *{{ item.key | regex_escape() }}:"
    line: "{{ item.key }}: {{ item.value }}"
    insertafter: '# Base Domain Settings Start'
  with_dict:
    'matrix_nginx_proxy_base_domain_homepage_enabled': 'false'
  when: (awx_customise_base_domain_website is defined) and awx_customise_base_domain_website|bool

- name: Record custom 'Customise Website + Access Export' variables locally on AWX
  delegate_to: 127.0.0.1
  lineinfile:
    path: '{{ awx_cached_matrix_vars }}'
    regexp: "^#? *{{ item.key | regex_escape() }}:"
    line: "{{ item.key }}: {{ item.value }}"
    insertafter: '# Custom Settings Start'
  with_dict:
    'awx_sftp_auth_method': '"{{ awx_sftp_auth_method }}"'
    'awx_sftp_password': '"{{ awx_sftp_password }}"'
    'awx_sftp_public_key': '"{{ awx_sftp_public_key }}"'

- name: Record custom 'Customise Website + Access Export' variables locally on AWX
  delegate_to: 127.0.0.1
  lineinfile:
    path: '{{ awx_cached_matrix_vars }}'
    regexp: "^#? *{{ item.key | regex_escape() }}:"
    line: "{{ item.key }}: {{ item.value }}"
    insertafter: '# Custom Settings Start'
  with_dict:
    'awx_customise_base_domain_website': '{{ awx_customise_base_domain_website }}'
  when: awx_customise_base_domain_website is defined

- name: Reload vars in matrix_vars.yml
  include_vars:
    file: '{{ awx_cached_matrix_vars }}'
  no_log: True

- name: Save new 'Customise Website + Access Export' survey.json to the AWX tower, template
  delegate_to: 127.0.0.1
  template:
    src: './roles/matrix-awx/surveys/configure_website_access_export.json.j2'
    dest: '/var/lib/awx/projects/clients/{{ member_id }}/{{ subscription_id }}/configure_website_access_export.json'
  when: awx_customise_base_domain_website is defined

- name: Copy new 'Customise Website + Access Export' survey.json to target machine
  copy:
    src: '/var/lib/awx/projects/clients/{{ member_id }}/{{ subscription_id }}/configure_website_access_export.json'
    dest:  '/matrix/awx/configure_website_access_export.json'
    mode: '0660'
  when: awx_customise_base_domain_website is defined

- name: Save new 'Customise Website + Access Export' survey.json to the AWX tower, template
  delegate_to: 127.0.0.1
  template:
    src: './roles/matrix-awx/surveys/access_export.json.j2'
    dest: '/var/lib/awx/projects/clients/{{ member_id }}/{{ subscription_id }}/access_export.json'
  when: awx_customise_base_domain_website is undefined

- name: Copy new 'Customise Website + Access Export' survey.json to target machine
  copy:
    src: '/var/lib/awx/projects/clients/{{ member_id }}/{{ subscription_id }}/access_export.json'
    dest:  '/matrix/awx/access_export.json'
    mode: '0660'
  when: awx_customise_base_domain_website is undefined

- name: Recreate 'Configure Website + Access Export' job template
  delegate_to: 127.0.0.1
  awx.awx.tower_job_template:
    name: "{{ matrix_domain }} - 1 - Configure Website + Access Export"
    description: "Configure base domain website settings and access the servers export."
    extra_vars: "{{ lookup('file', '/var/lib/awx/projects/clients/{{ member_id }}/{{ subscription_id }}/extra_vars.json') }}"
    job_type: run
    job_tags: "start,setup-nginx-proxy"
    inventory: "{{ member_id }}"
    project: "{{ member_id }} - Matrix Docker Ansible Deploy"
    playbook: setup.yml
    credential: "{{ member_id }} - AWX SSH Key"
    survey_enabled: true
    survey_spec: "{{ lookup('file', '/var/lib/awx/projects/clients/{{ member_id }}/{{ subscription_id }}/configure_website_access_export.json') }}"
    become_enabled: yes
    state: present
    verbosity: 1
    tower_host: "https://{{ awx_host }}"
    tower_oauthtoken: "{{ awx_session_token.ansible_facts.tower_token.token }}"
    validate_certs: yes
  when: awx_customise_base_domain_website is defined

- name: Recreate 'Access Export' job template
  delegate_to: 127.0.0.1
  awx.awx.tower_job_template:
    name: "{{ matrix_domain }} - 1 - Access Export"
    description: "Access the services export."
    extra_vars: "{{ lookup('file', '/var/lib/awx/projects/clients/{{ member_id }}/{{ subscription_id }}/extra_vars.json') }}"
    job_type: run
    job_tags: "start,setup-nginx-proxy"
    inventory: "{{ member_id }}"
    project: "{{ member_id }} - Matrix Docker Ansible Deploy"
    playbook: setup.yml
    credential: "{{ member_id }} - AWX SSH Key"
    survey_enabled: true
    survey_spec: "{{ lookup('file', '/var/lib/awx/projects/clients/{{ member_id }}/{{ subscription_id }}/access_export.json') }}"
    become_enabled: yes
    state: present
    verbosity: 1
    tower_host: "https://{{ awx_host }}"
    tower_oauthtoken: "{{ awx_session_token.ansible_facts.tower_token.token }}"
    validate_certs: yes
  when: awx_customise_base_domain_website is undefined

- name: If user doesn't define a awx_sftp_password, create a disabled 'sftp' account
  user:
    name: sftp
    comment: SFTP user to set custom web files and access servers export
    shell: /bin/false
    home: /home/sftp
    group: matrix
    password: '*'
    update_password: always
  when: awx_sftp_password|length == 0

- name: If user defines awx_sftp_password, enable account and set password on 'stfp' account
  user:
    name: sftp
    comment: SFTP user to set custom web files and access servers export
    shell: /bin/false
    home: /home/sftp
    group: matrix
    password: "{{ awx_sftp_password | password_hash('sha512') }}"
    update_password: always
  when: awx_sftp_password|length > 0

- name: Ensure group "sftp" exists
  group:
    name: sftp
    state: present

- name: adding existing user 'sftp' to group matrix
  user:
    name: sftp
    groups: sftp
    append: yes
  when: awx_customise_base_domain_website is defined

- name: Create the ro /chroot directory with sticky bit if it doesn't exist. (/chroot/website has matrix:matrix permissions and is mounted to nginx container)
  file:
    path: /chroot
    state: directory
    owner: root
    group: root
    mode: '1755'

- name: Ensure /chroot/website location exists.
  file:
    path: /chroot/website
    state: directory
    owner: matrix
    group: matrix
    mode: '0770'
  when: awx_customise_base_domain_website is defined

- name: Ensure /chroot/export location exists
  file:
    path: /chroot/export
    state: directory
    owner: sftp
    group: sftp
    mode: '0700'

- name: Ensure /home/sftp/.ssh location exists
  file:
    path: /home/sftp/.ssh
    state: directory
    owner: sftp
    group: sftp
    mode: '0700'

- name: Ensure /home/sftp/authorized_keys exists
  file:
    path: /home/sftp/.ssh/authorized_keys
    state: touch
    owner: sftp
    group: sftp
    mode: '0644'

- name: Clear authorized_keys file
  shell: echo "" > /home/sftp/.ssh/authorized_keys

- name: Insert public SSH key into authorized_keys file
  lineinfile:
    path: /home/sftp/.ssh/authorized_keys
    line: "{{ awx_sftp_public_key }}"
    owner: sftp
    group: sftp
    mode: '0644'
  when: (awx_sftp_public_key | length > 0) and (awx_sftp_auth_method == "SSH Key")
    
- name: Remove any existing Subsystem lines
  lineinfile:
    path: /etc/ssh/sshd_config
    state: absent
    regexp: '^Subsystem'

- name: Set SSH Subsystem State
  lineinfile:
    path: /etc/ssh/sshd_config
    insertafter: "^# override default of no subsystems"
    line: "Subsystem sftp internal-sftp"

- name: Add SSH Match User section for disabled auth
  blockinfile:
    path: /etc/ssh/sshd_config
    state: absent
    block: |
      Match User sftp
          ChrootDirectory /chroot
          PermitTunnel no
          X11Forwarding no
          AllowTcpForwarding no
          PasswordAuthentication yes
          AuthorizedKeysFile /home/sftp/.ssh/authorized_keys
  when: awx_sftp_auth_method == "Disabled"

- name: Add SSH Match User section for password auth
  blockinfile:
    path: /etc/ssh/sshd_config
    state: present
    block: |
      Match User sftp
          ChrootDirectory /chroot
          PermitTunnel no
          X11Forwarding no
          AllowTcpForwarding no
          PasswordAuthentication yes
  when: awx_sftp_auth_method == "Password"

- name: Add SSH Match User section for publickey auth
  blockinfile:
    path: /etc/ssh/sshd_config
    state: present
    block: |
      Match User sftp
          ChrootDirectory /chroot
          PermitTunnel no
          X11Forwarding no
          AllowTcpForwarding no
          AuthorizedKeysFile /home/sftp/.ssh/authorized_keys
  when: awx_sftp_auth_method == "SSH Key"

- name: Restart service ssh.service
  service:
    name: ssh.service
    state: restarted