##################################################
# DO Community Playbooks: LAMP on Ubuntu 18.04
##################################################
---
- hosts: all
  become: true
  vars_files:
    - vars/default.yml

  tasks:
    - name: Install prerequisites
      apt: 
        name: 'aptitude'
        update_cache: true

  #Swap partition in case of low RAM
    - name: Check if swap file exists
      stat:
        path: /swapfile
      register: swap_file_check

    - name: Create 2GB swap file (if not exists)
      command: fallocate -l 2G /swapfile
      when: not swap_file_check.stat.exists

    - name: Set permissions on swap file
      file:
        path: /swapfile
        owner: root
        group: root
        mode: '0600'
      when: not swap_file_check.stat.exists

    - name: Format swap file
      command: mkswap /swapfile
      when: not swap_file_check.stat.exists

    - name: Enable swap
      command: swapon /swapfile
      when: not swap_file_check.stat.exists

    - name: Create document root
      file:
        path: "/var/www/{{ http_host }}"
        state: directory
        owner: "{{ app_user }}"
        mode: '0755'

  # UFW Configuration
    - name: "UFW - Allow HTTP on port {{ http_port }}"
      ufw:
        rule: allow
        port: "{{ http_port }}"
        proto: tcp

    - name: Install munin
      apt:
        name:
          - munin-node
        state: present

  # TODO : d'ou est ajoute le fichier /etc/muning/munin-node.conf ?
  # Munin Configuration
  #https://stackoverflow.com/questions/77941169/ansible-add-line-update-etc-hosts-when-outdated
    - name: Install Munin Node
      ansible.builtin.lineinfile:
        path: /etc/munin/munin-node.conf
        regexp: '^allow'
        line: "allow ^127\\.0\\.0\\.1$"

    - name: Restart munin-node
      systemd:
        name: munin-node
        state: restarted
        enabled: yes

    - name: Install Docker plugins
      apt:
        name:
          - docker.io
          - docker-compose-v2
          - docker-buildx
        state: present

    - name: Ensure Docker service is running
      service:
        name: docker
        state: started
        enabled: yes

    - name: Create docker project directory
      file:
        path: "{{ docker_dir_path }}"
        state: directory
        mode: '0755'

    - name: Sync files content to VM
      ansible.posix.synchronize:
        src: "./files/"      # The trailing slash is important in rsync!
        dest: "{{ docker_dir_path }}/"
        recursive: yes

    - name: Tear down and run Docker Compose
      community.docker.docker_compose_v2:
        project_src: "{{ docker_dir_path }}/dockercompose"
        state: present
        remove_orphans: yes