---
- name: Install Duo Security on Debian
  when: ansible_os_family == 'Debian'
  block:
    - name: Add required packages
      become: true
      ansible.builtin.apt:
        name:
          - gpg
        state: present
        update_cache: true

    - name: Add Duo Key
      become: true
      ansible.builtin.apt_key:
        url: https://duo.com/DUO-GPG-PUBLIC-KEY.asc
        state: present

    # set architecture specific repo based on ansible_architecture
    - name: Set Duo Architecture (X86_64)
      ansible.builtin.set_fact:
        duo_arch: "[arch=amd64]"
      when: ansible_architecture == 'x86_64'

    - name: Set Duo Architecture (ARM64)
      ansible.builtin.set_fact:
        duo_arch: "[arch=arm64]"
      when: ansible_architecture == 'aarch64'

    - name: Add Duo source repository
      become: true
      ansible.builtin.apt_repository:
        filename: duo-security.list
        repo: deb {{ duo_arch }} {{ _duo_pkg_url }}/{{ ansible_distribution }} {{ ansible_distribution_release }} main
        state: present

    - name: Install Duo Unix Application Integration
      become: true
      ansible.builtin.apt:
        name: duo-unix
        state: present
        update_cache: true

- name: Install Duo Security on RedHat
  when: ansible_os_family == 'RedHat'
  block:
    - name: Add Duo Source (RedHat)
      become: true
      ansible.builtin.yum_repository:
        name: Duo Security
        description: Duo Security Repository
        baseurl: https://pkg.duosecurity.com/RHEL/$releasever/$basearch
        gpgcheck: true
        gpgkey: https://duo.com/DUO-GPG-PUBLIC-KEY.asc
        enabled: true

    - name: Install Duo Unix Application Integration
      become: true
      ansible.builtin.dnf:
        name: duo-unix
        state: present

- name: Install Duo config
  become: true
  ansible.builtin.template:
    src: login_duo.conf.j2
    dest: /etc/duo/login_duo.conf
    owner: sshd
    group: root
    mode: "0600"

- name: Get sshd Include config
  become: true
  ansible.builtin.command: grep -E "^Include " /etc/ssh/sshd_config
  register: grep_include
  changed_when: false
  failed_when: false

- name: Check if sshd_config.d exits
  ansible.builtin.stat:
    path: /etc/ssh/sshd_config.d
  register: sshd_config_d

- name: Fail if sshd_config.d does not exist
  when: not sshd_config_d.stat.exists or grep_include.rc != 0
  ansible.builtin.fail:
    msg: "sshd_config.d does not exist"

- name: Enable duo security for remote logins (sshd_config.d)
  become: true
  ansible.builtin.template:
    src: duo-security.conf.j2
    dest: /etc/ssh/sshd_config.d/02-duo-security.conf
    backup: true
    mode: "0600"
    owner: root
    group: root
    validate: sshd -t -f %s
  when: sshd_config_d.stat.exists and grep_include.rc == 0
  notify:
    - Restart sshd service
