---
- name: Check if YT-DLP master deployment directory exists
  stat:
    path: "{{ airflow_master_dir }}"
  register: master_dir_stat

- name: Ensure YT-DLP master deployment directory exists
  file:
    path: "{{ airflow_master_dir }}"
    state: directory
    owner: "{{ ssh_user }}"
    group: ytdl
    mode: '0755'
  become: yes
  when: not master_dir_stat.stat.exists

- name: "Log: Syncing YT-DLP service files"
  debug:
    msg: "Syncing YT-DLP service components (config generator, envoy/camoufox templates) to the master node."

- name: Sync YT-DLP service files to master
  synchronize:
    src: "../{{ item }}"
    dest: "{{ airflow_master_dir }}/"
    archive: yes
    recursive: yes
    rsync_path: "sudo rsync"
    rsync_opts: "{{ rsync_default_opts }}"
  loop:
    - "airflow/docker-compose-ytdlp-ops.yaml.j2"
    - "airflow/docker-compose.config-generate.yaml"
    - "airflow/generate_envoy_config.py"
    - "airflow/init-yt-service.sh"
    - "airflow/envoy.yaml.j2"

- name: Create .env file for YT-DLP master service
  template:
    src: "../../templates/.env.master.j2"
    dest: "{{ airflow_master_dir }}/.env"
    mode: "{{ file_permissions }}"
    owner: "{{ ssh_user }}"
    group: ytdl
  become: yes
  vars:
    service_role: "master"
    server_identity: "ytdlp-ops-service-mgmt"

- name: Make YT-DLP service init script executable
  file:
    path: "{{ airflow_master_dir }}/init-yt-service.sh"
    mode: "0755"
  become: yes

- name: Run YT-DLP service init script
  shell:
    cmd: "./init-yt-service.sh"
    chdir: "{{ airflow_master_dir }}"
  become: yes
  become_user: "{{ ssh_user }}"

- name: "Log: Generating YT-DLP service configurations"
  debug:
    msg: "Running the configuration generator script inside a temporary Docker container. This creates docker-compose and envoy files based on .env variables."

- name: Generate YT-DLP service configurations
  shell:
    cmd: "docker compose -f docker-compose.config-generate.yaml run --rm config-generator"
    chdir: "{{ airflow_master_dir }}"
  become: yes
  become_user: "{{ ssh_user }}"

- name: Pull YT-DLP service image
  community.docker.docker_image:
    name: "{{ ytdlp_ops_image }}"
    source: pull

- name: "Log: Starting YT-DLP management service"
  debug:
    msg: "Starting the YT-DLP management service on the master node. This service handles account and proxy management."

- name: Start YT-DLP master service
  community.docker.docker_compose_v2:
    project_src: "{{ airflow_master_dir }}"
    files:
      - "docker-compose-ytdlp-ops.yaml"
    state: present
    remove_orphans: true
