---
- name: Set local facts
  set_fact:
    pogojig_cache: /var/cache/pogojig

- name: Copy render script
  template:
      src: pogojig_generate.sh.j2
      dest: /usr/local/sbin/pogojig_generate.sh
      mode: ug+x

- name: Install packages into pogojig container
  shell: arch-chroot "{{pogojig_root}}" pacman -Syu --noconfirm python3 python-pip imagemagick unzip zip openscad inkscape make python-lxml xorg-server-xvfb

- name: Install python dependencies into pogojig container
  shell: arch-chroot "{{pogojig_root}}" pip install -U --upgrade-strategy=eager ezdxf xvfbwrapper

- name: Install pogojig
  synchronize:
    # FIXME: make this path configurable
      src: checkouts/pogojig/renderer/
      dest: "{{pogojig_root}}/var/lib/pogojig_renderer"
      group: no

- name: Copy webapp sources
  synchronize:
    # FIXME: make this path configurable
      src: checkouts/pogojig/webapp/
      dest: /var/lib/pogojig
      group: no
      owner: no

- name: Create web home for modified tracespace
  file:
      path: /var/lib/pogojig/pogospace
      state: directory
      owner: nginx
      group: nginx
      mode: 0550

- name: Unpack modified tracespace sources
  unarchive:
      src: resource/pogojig-tracespace.tar.gz
      dest: /var/lib/pogojig/pogospace
      extra_opts: [--strip-components=1]
      owner: nginx
      group: nginx

- name: Create uwsgi worker user and group
  user:
      name: uwsgi-pogojig
      create_home: no
      group: uwsgi
      password: '!'
      shell: /sbin/nologin
      system: yes

- name: Template webapp config
  template:
    src: pogojig.cfg.j2
    dest: /var/lib/pogojig/pogojig_prod.cfg
    owner: uwsgi-pogojig
    group: root
    mode: 0660

- name: Copy uwsgi config
  copy:
      src: uwsgi-pogojig.ini
      dest: /etc/uwsgi.d/pogojig.ini
      owner: uwsgi-pogojig
      group: uwsgi
      mode: 440

- name: Copy job processor systemd service config
  template:
      src: pogojig-job-processor.service.j2
      dest: /etc/systemd/system/pogojig-job-processor.service

- name: Enable uwsgi systemd socket
  systemd:
      daemon-reload: yes
      name: uwsgi-app@pogojig.socket
      enabled: yes

# FIXME the socket doesn't seem to work properly
- name: Enable uwsgi systemd service
  systemd:
      daemon-reload: yes
      name: uwsgi-app@pogojig.service
      enabled: yes

- name: Copy pogojig cache dir tmpfiles.d config
  template:
      src: tmpfiles-pogojig.conf.j2
      dest: /etc/tmpfiles.d/pogojig.conf
      owner: root
      group: root
      mode: 0644
  register: pogojig_tmpfiles_config

- name: Kick systemd tmpfiles service to create cache dir
  command: systemd-tmpfiles --create
  when: pogojig_tmpfiles_config is changed

- name: Create job queue db
  file:
    path: "{{pogojig_cache}}/job_queue.sqlite3"
    owner: root
    group: uwsgi
    mode: 0660
    state: touch

- name: Enable and launch job processor
  systemd:
      name: pogojig-job-processor.service
      enabled: yes
      state: restarted

