---
# tasks file for factorio
# Create the user and group to run the factorio server
- name: "{{ ansible_name_prefix }} Create OS group for factorio"
  group:
    name: "{{ service_group }}"
    state: present

- name: "{{ ansible_name_prefix }} Create OS user for factorio"
  user:
    name: "{{ service_user }}"
    state: present
    group: "{{ service_group }}"

# Download the factorio server version if needed
- name: "{{ ansible_name_prefix }} Make factorio bin source folder"
  file:
    path: "{{ server_sources }}"
    state: directory
    mode: u+rwx

- name: "{{ ansible_name_prefix }} Download factorio headless server from {{ download_url }}"
  get_url:
    url: "{{ download_url }}"
    dest: "{{ server_sources }}/factorio-{{ server_version }}.tar.gz"
    checksum: "{{ download_checksum }}"
  retries: 3
  delay: 5

# Copy the factorio version to the production location
- name: "{{ ansible_name_prefix }} Make factorio bin source folder"
  file:
    path: "{{ service_root }}"
    state: directory
    mode: u+rwx

- name: "{{ ansible_name_prefix }} Extract Factorio headless server to {{ server_sources }}"
  unarchive:
    src: "{{ server_sources }}/factorio-{{ server_version }}.tar.gz"
    copy: no
    dest: "{{ service_root }}"
    creates: "{{ service_root }}/factorio"

- name: "{{ ansible_name_prefix }} Make sure game save directory exists"
  file:
    path: "{{ service_root }}/factorio/saves"
    state: directory
    mode: u+rwx

# Create the various settings files
- name: "{{ ansible_name_prefix }} Set server settings"
  include: set-server-settings.yml

- name: "{{ ansible_name_prefix }} Set server whitelist"
  include: set-server-whitelist.yml

- name: "{{ ansible_name_prefix }} Set map gen settings"
  include: set-map-gen-settings.yml

- name: "{{ ansible_name_prefix }} Set map settings"
  include: set-map-settings.yml

# Create the save if one doesn't already exist
- name: "{{ ansible_name_prefix }} Create default save file"
  command: "{{ service_root }}/factorio/bin/x64/factorio --create {{ factorio_target_save }}"
  args:
    creates: "{{ factorio_target_save }}"

# Set the permissions so only the user has access
- name: "{{ ansible_name_prefix }} Make {{ service_root }} owned by {{ service_user }}"
  file:
    path: "{{ service_root }}"
    state: directory
    owner: "{{ service_user }}"
    group: "{{ service_group }}"
    recurse: yes

# Create the service
- name: "{{ ansible_name_prefix }} Create service file"
  template:
    src: service-template.service.j2
    dest: /etc/systemd/system/{{ service_name }}.service
    mode: "u=rwx,g=r,o=r"
  vars:
    bin: "{{ service_root }}/factorio/bin/x64/factorio"
    save: "{{ factorio_target_save }}"
    description: "Factorio {{ server_version }} {{ service_name }}"
  notify:
    - Reload factorio server (daemon_reload)
    - Restart factorio service