---
- name: mediaserver install
  ansible.builtin.apt:
    force_apt_get: true
    install_recommends: false
    name: "{{ server_packages }}"
  register: apt_status
  retries: 60
  until: apt_status is success or ('Failed to lock apt for exclusive operation' not in apt_status.msg and '/var/lib/dpkg/lock' not in apt_status.msg)

- name: fetch ssh public key
  register: root_ssh_pubkey
  ansible.builtin.slurp:
    path: /root/.ssh/id_ed25519.pub
  tags: always

- name: register ssh public key as an ansible fact
  ansible.builtin.set_fact:
    pubkey: "{{ root_ssh_pubkey['content'] | b64decode }}"
  tags: always

- name: share ssh public key between cluster members
  loop: "{{ groups['mediaserver'] }}"
  ansible.posix.authorized_key:
    user: root
    key: "{{ hostvars[item]['pubkey'] }}"
  tags: always

- name: Update the MS configuration with the celerity server IP
  ansible.builtin.lineinfile:
    path: /etc/mediaserver/msconf.py
    regexp: "^CELERITY_SERVER_URL = "
    line: CELERITY_SERVER_URL = 'https://{{ server_celerity_server_url }}:6200'
    create: true
    owner: root
    group: root
    # 644 as all the instances must reach this file
    # The instances cannot be in a common group as of now => https://redmine.ubicast.net/issues/33046
    mode: "0644"

- name: Update the MS configuration with the celerity server secret
  ansible.builtin.lineinfile:
    path: /etc/mediaserver/msconf.py
    regexp: "^CELERITY_SIGNING_KEY = "
    line: CELERITY_SIGNING_KEY = '{{ server_celerity_signing_key }}'
    create: true
    owner: root
    group: root
    # 644 as all the instances must reach this file
    # The instances cannot be in a common group as of now => https://redmine.ubicast.net/issues/33046
    mode: "0644"

- name: create instances
  loop: "{{ server_instances }}"
  ansible.builtin.command:
    cmd: >
      mscontroller.py add -u '{{ item.name }}' -t '{
        "id": "{{ item.ms_id }}",
        "domain": "{{ item.ms_server_name }}",
        "api_key": "{{ item.ms_api_key }}",
        "secret": "{{ envsetup_ms_secret | d("") }}",
        "superuser_pwd": "{{ item.ms_superuser_pwd }}",
        "admin_pwd": "{{ item.ms_admin_pwd }}",
        "skyreach_url": "{{ item.cm_server_name }}"
      }'
    creates: /etc/nginx/sites-available/mediaserver-{{ item.name }}.conf
  throttle: 1

- name: synchronize configuration between servers # noqa command-instead-of-module
  # Cannot use the ansible synchronization module, cause there is no way to set a destination IP intead of the destination ansible hostname
  # noqa command-instead-of-module = warn to use the synchronization module instead of rsync in the command module
  when:
    - groups['mediaserver'] | length > 1
    - inventory_hostname != groups['mediaserver'][0]
  loop:
    - /etc/mediaserver
    - /etc/nginx
    - /etc/celerity
    - /etc/sysusers.d
    - /var/www
  ansible.builtin.command: |
    rsync \
      -avh \
      -e "ssh -o StrictHostKeyChecking=no" \
      --delete \
      "{{ item }}/" \
      "root@{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}:{{ item }}/"
  notify:
    - restart systemd-sysusers
    - restart nginx
    - restart mediaserver
  delegate_to: "{{ groups['mediaserver'][0] }}"
  changed_when: false
  tags: mediaserver-synchronize

- name: synchronize letsencrypt configuration between servers # noqa command-instead-of-module
  # Cannot use the ansible synchronization module, cause there is no way to set a destination IP intead of the destination ansible hostname
  # noqa command-instead-of-module = warn to use the synchronization module instead of rsync in the command module
  when:
    - groups['mediaserver'] | length > 1
    - inventory_hostname != groups['mediaserver'][0]
    - letsencrypt_enabled | d(false)
  loop:
    - /etc/letsencrypt
  ansible.builtin.command: |
    rsync \
      -avh \
      -e "ssh -o StrictHostKeyChecking=no" \
      --delete \
      "{{ item }}/" \
      "root@{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}:{{ item }}/"
  notify:
    - restart nginx
  delegate_to: "{{ groups['mediaserver'][0] }}"
  changed_when: false
  tags: mediaserver-synchronize

- name: configure email sender address
  notify:
    - restart mediaserver
  ansible.builtin.lineinfile:
    path: /etc/mediaserver/msconf.py
    backup: true
    create: true
    owner: root
    group: root
    # 644 as all the instances must reach this file
    # The instances cannot be in a common group as of now => https://redmine.ubicast.net/issues/33046
    mode: "0644"
    regexp: ^#? ?DEFAULT_FROM_EMAIL.*
    line: DEFAULT_FROM_EMAIL = '{{ server_email_sender }}'
    validate: python3 -m py_compile %s

- name: configure domain name in nginx conf
  notify: restart nginx
  loop: "{{ server_instances }}"
  ansible.builtin.replace:
    path: /etc/nginx/sites-available/mediaserver-{{ item.name }}.conf
    regexp: ^(\s*server_name).*;$
    replace: \1 {{ item.ms_server_name }};
    backup: true

- name: configure domain name in database
  loop: "{{ server_instances }}"
  ansible.builtin.shell:
    cmd: |
      python3 /usr/lib/python3/dist-packages/mediaserver/scripts/mssiteconfig.py {{ item.name }} site_url=https://{{ item.ms_server_name }} ;
      mscontroller.py restart -u {{ item.name }} ;
      touch /etc/mediaserver/.{{ item.ms_server_name }}.mssiteconfig.log ;
    creates: /etc/mediaserver/.{{ item.ms_server_name }}.mssiteconfig.log

- name: reset service resources
  loop: "{{ server_instances }}"
  ansible.builtin.shell:
    cmd: |
      python3 /usr/lib/python3/dist-packages/mediaserver/scripts/reset_service_resources.py {{ item.name }} local ;
      mscontroller.py restart -u {{ item.name }} ;
      touch /etc/mediaserver/.{{ item.ms_server_name }}.reset_service_resources.log ;
    creates: /etc/mediaserver/.{{ item.ms_server_name }}.reset_service_resources.log

- name: add realip configuration for LoadBalancer in HA configuration
  notify: restart nginx
  when:
    - groups['mediaserver'] | length > 1
    - real_ip_from | length > 0
  ansible.builtin.template:
    src: realip.conf.j2
    dest: /etc/nginx/conf.d/realip.conf
    mode: "644"

- name: ensure mediaserver is running
  ansible.builtin.service:
    name: mediaserver
    enabled: true
    state: started

# FIREWALL

- name: firewall
  when: server_firewall_enabled
  vars:
    ferm_rules_filename: "{{ server_ferm_rules_filename }}"
    ferm_input_rules: "{{ server_ferm_input_rules }}"
    ferm_output_rules: "{{ server_ferm_output_rules }}"
    ferm_global_settings: "{{ server_ferm_global_settings }}"
  ansible.builtin.include_role:
    name: ferm-configure

- name: flush handlers
  ansible.builtin.meta: flush_handlers
