---
# deploy-ansipa-modules.yml — deploy the module auto-installer to enrolled hosts.
#
# Prerequisites on target hosts:
#   - FreeIPA client enrolled (sssd running, ipa command available)
#   - A non-root user with yay access (set ANSIPA_USER in /etc/ansipa-modules.conf)
#
# Usage:
#   ansible-playbook -i inventory deploy-ansipa-modules.yml
#   ansible-playbook -i inventory deploy-ansipa-modules.yml -e ansipa_user=amir
#
# FreeIPA host group convention:
#   Create host groups named  ansipa-module-<name>  (e.g. ansipa-module-docker)
#   and add hosts to them. The timer will apply the matching module automatically.

- name: Deploy FreeIPA module auto-installer
  hosts: all
  become: yes

  vars:
    ansipa_user: "{{ lookup('env', 'ANSIPA_USER') | default('', true) }}"
    modules_dir: /usr/local/lib/ansipa-modules
    state_dir: /var/lib/ansipa-modules

  tasks:

    - name: Create module directories
      file:
        path: "{{ item }}"
        state: directory
        mode: '0755'
      loop:
        - "{{ modules_dir }}"
        - "{{ state_dir }}"

    - name: Write /etc/ansipa-modules.conf
      copy:
        dest: /etc/ansipa-modules.conf
        mode: '0644'
        content: |
          # ansipa-modules configuration
          # ANSIPA_USER: non-root user used to run the AUR helper (yay).
          # Leave blank to auto-detect the first non-system user.
          ANSIPA_USER={{ ansipa_user }}
          MODULES_DIR={{ modules_dir }}
          STATE_DIR={{ state_dir }}
      when: ansipa_user != ""

    - name: Deploy main module installer script
      copy:
        src: ansipa-install-modules.sh
        dest: /usr/local/bin/ansipa-install-modules.sh
        mode: '0755'

    - name: Deploy module scripts
      copy:
        src: "{{ item }}"
        dest: "{{ modules_dir }}/{{ item | basename }}"
        mode: '0755'
      with_fileglob:
        - "../optional-Modules/apps/*.sh"

    - name: Install systemd service
      copy:
        dest: /etc/systemd/system/ansipa-install-modules.service
        mode: '0644'
        content: |
          [Unit]
          Description=Apply setup modules based on FreeIPA ansipa-module-* host groups
          After=network-online.target sssd.service
          Wants=network-online.target

          [Service]
          Type=oneshot
          ExecStart=/usr/local/bin/ansipa-install-modules.sh
          StandardOutput=journal
          StandardError=journal

    - name: Install systemd timer
      copy:
        dest: /etc/systemd/system/ansipa-install-modules.timer
        mode: '0644'
        content: |
          [Unit]
          Description=Periodic FreeIPA module sync

          [Timer]
          OnBootSec=3min
          OnUnitActiveSec=30min

          [Install]
          WantedBy=timers.target

    - name: Reload systemd
      command: systemctl daemon-reload

    - name: Enable and start module timer
      systemd:
        name: ansipa-install-modules.timer
        enabled: yes
        state: started
