---
- name: Configure mockupAWS Production Server
  hosts: production
  become: yes
  vars:
    app_name: mockupaws
    app_user: mockupaws
    app_group: mockupaws
    app_dir: /opt/mockupaws
    data_dir: /data/mockupaws
    
  tasks:
    #------------------------------------------------------------------------------
    # System Updates
    #------------------------------------------------------------------------------
    - name: Update system packages
      apt:
        update_cache: yes
        upgrade: dist
        autoremove: yes
      when: ansible_os_family == "Debian"
      tags: [system]

    - name: Install required packages
      apt:
        name:
          - apt-transport-https
          - ca-certificates
          - curl
          - gnupg
          - lsb-release
          - software-properties-common
          - python3-pip
          - python3-venv
          - nginx
          - fail2ban
          - ufw
          - htop
          - iotop
          - ncdu
          - tree
          - jq
        state: present
        update_cache: yes
      when: ansible_os_family == "Debian"
      tags: [system]

    #------------------------------------------------------------------------------
    # User Setup
    #------------------------------------------------------------------------------
    - name: Create application group
      group:
        name: "{{ app_group }}"
        state: present
      tags: [user]

    - name: Create application user
      user:
        name: "{{ app_user }}"
        group: "{{ app_group }}"
        home: "{{ app_dir }}"
        shell: /bin/bash
        state: present
      tags: [user]

    #------------------------------------------------------------------------------
    # Docker Installation
    #------------------------------------------------------------------------------
    - name: Add Docker GPG key
      apt_key:
        url: https://download.docker.com/linux/ubuntu/gpg
        state: present
      when: ansible_os_family == "Debian"
      tags: [docker]

    - name: Add Docker repository
      apt_repository:
        repo: "deb [arch=amd64] https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable"
        state: present
      when: ansible_os_family == "Debian"
      tags: [docker]

    - name: Install Docker
      apt:
        name:
          - docker-ce
          - docker-ce-cli
          - containerd.io
          - docker-compose-plugin
        state: present
        update_cache: yes
      when: ansible_os_family == "Debian"
      tags: [docker]

    - name: Add user to docker group
      user:
        name: "{{ app_user }}"
        groups: docker
        append: yes
      tags: [docker]

    - name: Enable and start Docker
      systemd:
        name: docker
        enabled: yes
        state: started
      tags: [docker]

    #------------------------------------------------------------------------------
    # Directory Structure
    #------------------------------------------------------------------------------
    - name: Create application directories
      file:
        path: "{{ item }}"
        state: directory
        owner: "{{ app_user }}"
        group: "{{ app_group }}"
        mode: '0755'
      loop:
        - "{{ app_dir }}"
        - "{{ app_dir }}/config"
        - "{{ app_dir }}/logs"
        - "{{ data_dir }}"
        - "{{ data_dir }}/postgres"
        - "{{ data_dir }}/redis"
        - "{{ data_dir }}/backups"
        - "{{ data_dir }}/reports"
      tags: [directories]

    #------------------------------------------------------------------------------
    # Firewall Configuration
    #------------------------------------------------------------------------------
    - name: Configure UFW
      ufw:
        rule: "{{ item.rule }}"
        port: "{{ item.port }}"
        proto: "{{ item.proto | default('tcp') }}"
      loop:
        - { rule: allow, port: 22 }
        - { rule: allow, port: 80 }
        - { rule: allow, port: 443 }
      tags: [firewall]

    - name: Enable UFW
      ufw:
        state: enabled
        default_policy: deny
      tags: [firewall]

    #------------------------------------------------------------------------------
    # Fail2ban Configuration
    #------------------------------------------------------------------------------
    - name: Configure fail2ban
      template:
        src: fail2ban.local.j2
        dest: /etc/fail2ban/jail.local
        mode: '0644'
      notify: restart fail2ban
      tags: [security]

    - name: Enable and start fail2ban
      systemd:
        name: fail2ban
        enabled: yes
        state: started
      tags: [security]

    #------------------------------------------------------------------------------
    # Nginx Configuration
    #------------------------------------------------------------------------------
    - name: Remove default Nginx site
      file:
        path: /etc/nginx/sites-enabled/default
        state: absent
      tags: [nginx]

    - name: Configure Nginx
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        mode: '0644'
      notify: restart nginx
      tags: [nginx]

    - name: Create Nginx site configuration
      template:
        src: mockupaws.conf.j2
        dest: /etc/nginx/sites-available/mockupaws
        mode: '0644'
      tags: [nginx]

    - name: Enable Nginx site
      file:
        src: /etc/nginx/sites-available/mockupaws
        dest: /etc/nginx/sites-enabled/mockupaws
        state: link
      notify: reload nginx
      tags: [nginx]

    - name: Enable and start Nginx
      systemd:
        name: nginx
        enabled: yes
        state: started
      tags: [nginx]

    #------------------------------------------------------------------------------
    # SSL Certificate (Let's Encrypt)
    #------------------------------------------------------------------------------
    - name: Install certbot
      apt:
        name: certbot
        state: present
      tags: [ssl]

    - name: Check if certificate exists
      stat:
        path: "/etc/letsencrypt/live/{{ domain_name }}/fullchain.pem"
      register: cert_file
      tags: [ssl]

    - name: Obtain SSL certificate
      command: >
        certbot certonly --standalone 
        -d {{ domain_name }} 
        -d www.{{ domain_name }}
        --agree-tos 
        --non-interactive 
        --email {{ admin_email }}
      when: not cert_file.stat.exists
      tags: [ssl]

    - name: Setup certbot renewal cron
      cron:
        name: "Certbot Renewal"
        minute: "0"
        hour: "3"
        job: "/usr/bin/certbot renew --quiet --deploy-hook 'systemctl reload nginx'"
      tags: [ssl]

    #------------------------------------------------------------------------------
    # Backup Scripts
    #------------------------------------------------------------------------------
    - name: Create backup script
      template:
        src: backup.sh.j2
        dest: "{{ app_dir }}/scripts/backup.sh"
        owner: "{{ app_user }}"
        group: "{{ app_group }}"
        mode: '0750'
      tags: [backup]

    - name: Setup backup cron
      cron:
        name: "mockupAWS Backup"
        minute: "0"
        hour: "2"
        user: "{{ app_user }}"
        job: "{{ app_dir }}/scripts/backup.sh"
      tags: [backup]

    #------------------------------------------------------------------------------
    # Log Rotation
    #------------------------------------------------------------------------------
    - name: Configure logrotate
      template:
        src: logrotate.conf.j2
        dest: /etc/logrotate.d/mockupaws
        mode: '0644'
      tags: [logging]

    #------------------------------------------------------------------------------
    # Monitoring Agent
    #------------------------------------------------------------------------------
    - name: Download Prometheus Node Exporter
      get_url:
        url: "https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-amd64.tar.gz"
        dest: /tmp/node_exporter.tar.gz
      tags: [monitoring]

    - name: Extract Node Exporter
      unarchive:
        src: /tmp/node_exporter.tar.gz
        dest: /usr/local/bin
        remote_src: yes
        extra_opts: [--strip-components=1]
        include: ["*/node_exporter"]
      tags: [monitoring]

    - name: Create Node Exporter service
      template:
        src: node-exporter.service.j2
        dest: /etc/systemd/system/node-exporter.service
        mode: '0644'
      tags: [monitoring]

    - name: Enable and start Node Exporter
      systemd:
        name: node-exporter
        enabled: yes
        state: started
        daemon_reload: yes
      tags: [monitoring]

  handlers:
    - name: restart fail2ban
      systemd:
        name: fail2ban
        state: restarted

    - name: restart nginx
      systemd:
        name: nginx
        state: restarted

    - name: reload nginx
      systemd:
        name: nginx
        state: reloaded
