---
- name: Update apt cache
  ansible.builtin.apt:
    update_cache: true
    cache_valid_time: 3600

- name: Install essential packages
  ansible.builtin.apt:
    name:
      - apt-transport-https
      - ca-certificates
      - curl
      - gnupg
      - lsb-release
      - ufw
      - fail2ban
      - git
    state: present

# Firewall
- name: Configure UFW rules
  ansible.builtin.shell: |
    ufw allow 22/tcp
    ufw allow 80/tcp
    ufw allow 443/tcp
    ufw allow {{ forgejo_ssh_port | default(2222) }}/tcp
    ufw --force enable
    ufw default deny incoming
  changed_when: false

# Fail2ban
- name: Enable fail2ban
  ansible.builtin.systemd:
    name: fail2ban
    enabled: true
    state: started

# Docker
- name: Ensure keyrings directory exists
  ansible.builtin.file:
    path: /etc/apt/keyrings
    state: directory
    mode: "0755"

- name: Add Docker GPG key
  ansible.builtin.shell:
    cmd: curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc && chmod 644 /etc/apt/keyrings/docker.asc
    creates: /etc/apt/keyrings/docker.asc

- name: Add Docker apt repository
  ansible.builtin.apt_repository:
    repo: "deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable"
    state: present

- name: Install Docker
  ansible.builtin.apt:
    name:
      - docker-ce
      - docker-ce-cli
      - containerd.io
      - docker-buildx-plugin
    state: present
    update_cache: true

- name: Start Docker
  ansible.builtin.systemd:
    name: docker
    enabled: true
    state: started

# Docker network
- name: Create Docker network
  ansible.builtin.shell: docker network inspect {{ docker_network }} >/dev/null 2>&1 || docker network create {{ docker_network }}
  changed_when: false

# SSH key (for cloning from Forgejo)
- name: Generate SSH key
  ansible.builtin.shell:
    cmd: ssh-keygen -t ed25519 -f /root/.ssh/id_ed25519 -N "" -q
    creates: /root/.ssh/id_ed25519

- name: Read SSH public key
  ansible.builtin.command: cat /root/.ssh/id_ed25519.pub
  register: ssh_public_key
  changed_when: false

- name: Show SSH public key
  ansible.builtin.debug:
    msg: "Add this SSH key to Forgejo (Settings > SSH Keys): {{ ssh_public_key.stdout }}"

# App directories
- name: Create app directories
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    mode: "0755"
  loop:
    - /opt/church-website
    - "{{ repo_dir }}"
    - "{{ envs_dir }}"
    - "{{ scripts_dir }}"

- name: Create environment directories
  ansible.builtin.file:
    path: "{{ envs_dir }}/{{ item.name }}"
    state: directory
    mode: "0750"
  loop: "{{ app_environments }}"
  loop_control:
    label: "{{ item.name }}"
