---
###########################
# T-Pot Sensor Deployment #
###########################

- name: T-POT Sensor Deployment
  hosts: all
  vars:
    local_nginx_cert_path: "~/tpotce/data/nginx/cert/nginx.crt"
    remote_cert_path: "~/tpotce/data/hive.crt"
    remote_sensor_yml_path: "~/tpotce/compose/sensor.yml"
    remote_docker_compose_path: "~/tpotce/docker-compose.yml"
    env_file_path: "~/tpotce/.env"

  tasks:
    - name: Ensure the destination directory exists
      ansible.builtin.file:
        path: "{{ remote_cert_path | dirname }}"
        state: directory
        mode: '770'

    - name: Copy nginx.crt from local to remote host
      ansible.builtin.copy:
        src: "{{ local_nginx_cert_path }}"
        dest: "{{ remote_cert_path }}"

    - name: Copy sensor.yml to docker-compose.yml on the remote host
      ansible.builtin.command:
        cmd: "cp {{ remote_sensor_yml_path }} {{ remote_docker_compose_path }}"

    - name: Update T-POT_HIVE_USER in .env
      ansible.builtin.lineinfile:
        path: "{{ env_file_path }}"
        regexp: '^TPOT_HIVE_USER='
        line: 'TPOT_HIVE_USER={{ lookup("env", "myTPOT_HIVE_USER") }}'

    - name: Update T-POT_HIVE_IP in .env
      ansible.builtin.lineinfile:
        path: "{{ env_file_path }}"
        regexp: '^TPOT_HIVE_IP='
        line: 'TPOT_HIVE_IP={{ lookup("env", "myTPOT_HIVE_IP") }}'

    - name: Ensure T-POT_TYPE is set to SENSOR in .env
      ansible.builtin.lineinfile:
        path: "{{ env_file_path }}"
        regexp: '^TPOT_TYPE='
        line: 'TPOT_TYPE=SENSOR'
        create: yes

    - name: Ensure WEB_USER is empty in .env
      ansible.builtin.lineinfile:
        path: "{{ env_file_path }}"
        regexp: '^WEB_USER='
        line: 'WEB_USER='
        create: yes

    - name: Ensure LS_WEB_USER is empty in .env
      ansible.builtin.lineinfile:
        path: "{{ env_file_path }}"
        regexp: '^LS_WEB_USER='
        line: 'LS_WEB_USER='
        create: yes

    - name: Reboot the sensor
      become: yes
      ansible.builtin.reboot:
        reboot_timeout: 600
        pre_reboot_delay: 0
        post_reboot_delay: 0
        msg: "Reboot initiated by Ansible for T-Pot sensor deployment."
        test_command: "uptime"
