---
- name: Install Etebase server
  hosts: ulna

  tasks:
  - name: Python3 and virtualenv
    ansible.builtin.apt:
      name: python3-virtualenv
      state: present
    become: true

  - name: Create etebase group
    ansible.builtin.group:
      name: etebase
      state: present
    become: true

  - name: Create etebase user
    ansible.builtin.user:
      name: etebase
      group: etebase
      comment: Etebase user
      password: '!'
      system: true
      home: "{{ etebase_home_dir }}"
      state: present
    become: true

  - name: Clone etebase repo
    ansible.builtin.git:
      repo: "https://github.com/etesync/server.git"
      dest: "{{ etebase_home_dir }}/etebase"
      single_branch: true
      force: true
    become: true
    become_user: etebase

  - name: Install etebase python requirements
    ansible.builtin.pip:
      requirements: "{{ etebase_home_dir }}/etebase/requirements.txt"
      virtualenv: "{{ etebase_home_dir }}/venv"
      state: present
    become: true
    become_user: etebase

  - name: Install uvicorn inside venv
    ansible.builtin.pip:
      name: "uvicorn[standard]"
      virtualenv: "{{ etebase_home_dir }}/venv"
      state: present
    become: true
    become_user: etebase

  - name: Setup configuration
    ansible.builtin.template:
      src: "templates/etebase-server.ini.j2"
      dest: "{{ etebase_home_dir }}/etebase/etebase-server.ini"
      mode: "0640"
      group: etebase
      owner: etebase
    become: true
    become_user: etebase

  - name: Create directories
    ansible.builtin.file:
      path: "{{ item.dir }}"
      mode: "{{ item.mode }}"
      owner: etebase
      group: "{{ item.group | default('etebase') }}"
      state: directory
    loop:
      - { dir: "{{ etebase_home_dir }}/media", mode: "0750" }
      - { dir: "{{ etebase_home_dir }}/secret", mode: "0750" }
      - { dir: "{{ etebase_home_dir }}/static", mode: "0750", group: "www-data" }
      - { dir: "/var/run/etebase", mode: "0750", group: "www-data" }
    become: true

  - name: Run manage.py migrate
    ansible.builtin.command:
      cmd: "{{ etebase_home_dir }}/venv/bin/python3 ./manage.py migrate"
      chdir: "{{ etebase_home_dir }}/etebase"
    become: true
    become_user: etebase

      # FIXME: Stuck?
      # - name: Run manage.py collectstatic
      #   ansible.builtin.command:
      #     cmd: "{{ etebase_home_dir }}/venv/bin/python3 ./manage.py collectstatic"
      #     chdir: "{{ etebase_home_dir }}/etebase"
      #   become: true
      #   become_user: etebase

  - name: Setup systemd service
    ansible.builtin.template:
      src: "templates/etebase.service.j2"
      dest: "/etc/systemd/system/etebase.service"
    become: true

  - name: (Re)start the systemd service
    ansible.builtin.systemd:
      state: restarted
      name: etebase
      enabled: true
      daemon_reload: true
    become: true
