---
- name: Acquiring home of current user
  when: ansible_facts["system"] == "Linux"
  ansible.builtin.shell:
    cmd: "echo ~{{ ansible_user }}"
  register: ansible_user_home
- name: Acquiring current user
  when: ansible_facts["system"] == "Linux"
  ansible.builtin.shell:
    cmd: "echo {{ ansible_user }}"
  register: current_user
- name: Informing user of requirement of two main domains 
  when: (certbot.domains | length) < 2 or (certbot.domains | length) > 2
  ansible.builtin.fail:
    msg: Only two domains allowed and required
- name: Informing user of requirement at least one wildcard
  when: (certbot.domains | select("regex", "^\\*\\.") | list | length) == 0
  ansible.builtin.fail:
    msg: At least one of the FQDNs must have a wildcard
# - name: Setting the FQDN for development
#   when: compose.mode == "dev"
#   ansible.builtin.set_fact:
#     web_fqdn: "{{ (certbot.domains | map('regex_replace', '\\.([^\\.]*)$', '.test') | reject('regex', '^\\*\\.') | list)[0] }}"
- name: Setting the FQDN
  # when: compose.mode == "prod"
  ansible.builtin.set_fact:
    web_fqdn: "{{ (certbot.domains | reject('regex', '^\\*\\.') | list)[0] }}"
- name: Creating directory to store configuration file
  ansible.builtin.file:
    path: "{{ ansible_user_home.stdout }}/.aria2"
    recurse: true
    owner: "{{ ansible_user }}"
    group: "{{ ansible_user }}"
    mode: "755"
    state: directory
- name: Configuring Aria2
  become: true
  become_user: "{{ current_user.stdout }}"
  ansible.builtin.template:
    src: user/aria2/aria2.conf.j2
    dest: "{{ ansible_user_home.stdout }}/.aria2/aria2.conf"
    owner: "{{ ansible_user }}"
    group: "{{ ansible_user }}"
    mode: "644"
    force: true
    backup: true
    # validate: "aria2c --check"
- name: Setting up Aria2 as a service
  when: aria.rpc.enabled and not aria.containerized
  block:
    - name: Creating a user SystemD service unit for Aria2
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.copy:
        src: user/config/systemd/user/aria2cd.service
        dest: "{{ ansible_user_home.stdout }}/.config/systemd/user/aria2cd.service"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
    - name: Starting and enabling user SystemD service unit for Aria2
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.systemd_service:
        name: aria2cd
        scope: user
        enabled: true
        state: started
        daemon_reload: true