---
- name: Use production secrets
  include_vars: "defaults/production_secrets.yml"
  when: use_production_secrets

- name: Enforce proper passwords
  assert:
    that: not (item.pw | b64decode).startswith('CHANGE_TO_PROPER_')
    fail_msg: "{{ item.name }} is not set to a proper password!"
    quiet: true
  with_items:
    - name: psql_password
      pw: "{{ psql_password | b64encode }}"
    - name: server_default_password
      pw: "{{ server_default_password | b64encode }}"
  ignore_errors: True

- name: Install dependencies
  include_tasks: server_dependencies.yml
  tags: dependencies

- name: Prepare system for installation
  include_tasks: server_prepare.yml
  tags: prepare

- name: Install Minetest
  include_tasks: install_minetest.yml
  tags: build

- name: Create config
  include_tasks: config_minetest.yml
  tags: config

- name: Enable Minetest service
  ansible.builtin.systemd:
    name: minetest
    enabled: true
    daemon-reload: true
  become: true

- name: Install mods
  include_tasks: install_mods.yml
  tags: mods

- name: Stop minetest
  ansible.builtin.systemd:
    name: minetest
    state: stopped
  become: true
  when: minetest_build.changed or game_repo.changed or mods_repo.changed

- name: Dissolve overlayfs structure
  ansible.posix.mount:
    path: "{{ minetest_base_dir }}/minetest"
    state: absent
  become: true
  when: minetest_build.changed or game_repo.changed or mods_repo.changed

- name: Create read only overlayfs structure
  ansible.posix.mount:
    path: "{{ minetest_base_dir }}/minetest"
    src: overlay # not needed because the options take care of everything, but still required by ansible
    opts: "lowerdir={{ lower_dirs | reverse | zip_longest([],fillvalue=minetest_base_dir) | map('reverse') | map('join', '/') | join(':') }}"
    state: mounted
    fstype: overlay
  become: true
  vars:
    lower_dirs:
      - .overlayfs/src_root
      - .overlayfs/game_root
      - .overlayfs/mods_root
      - .overlayfs/conf_root

- name: Run handlers
  meta: flush_handlers

- name: Start minetest
  ansible.builtin.systemd:
    name: minetest
    state: started
  become: true
