- name: Surveyor prerequisites
  apt:
    pkg:
      - python3-psycopg2

- name: "surveyor-web dependencies"
  block:
    - name: "Base surveyor-web dependencies"
      apt:
        pkg:
          - uwsgi
          - uwsgi-plugin-python3
          - python3-flask
          - python3-sqlalchemy
        state: present
      register: surveyor_web_deps_apt

    - name: "Remove flask-sqlalchemy that is too old from Debian"
      apt:
        pkg:
          - python3-flask-sqlalchemy
        state: absent

    - name: "Install newer flask-sqlalchemy using PIP"
      pip:
        name: flask-sqlalchemy
        version: 2.5.1
      register: surveyor_web_deps_pip0

    - name: "Install newer flask-migrate using PIP"
      pip:
        name: flask-migrate
        version: 2.7.0
      register: surveyor_web_deps_pip1

  when: run_surveyor_web

- name: Surveyor benchmarking user
  group:
    name: surveyor
    gid: 753

- name: Surveyor benchmarking user
  user:
    name: surveyor
    group: surveyor
    uid: 753
    shell: /bin/bash
    home: /var/obj/surveyor

- name: Surveyor web user
  user:
    name: surveyor-web
    group: surveyor
    uid: 754
    shell: /bin/bash
    home: /srv/surveyor

- name: Extra permissions for xmrazek7
  copy:
    dest: /etc/sudoers.d/xmrazek7
    content: |
      xmrazek7 ALL=NOPASSWD: /bin/systemctl restart quickpoll,/bin/systemctl start quickpoll,/bin/systemctl stop quickpoll,/bin/systemctl restart surveyor,/bin/systemctl start surveyor,/bin/systemctl stop surveyor,/bin/systemctl restart surveyor-web,/bin/systemctl start surveyor-web,/bin/systemctl stop surveyor-web
      xmrazek7 ALL=(quickpoll) NOPASSWD: ALL
      xmrazek7 ALL=(surveyor) NOPASSWD: ALL
      xmrazek7 ALL=(surveyor-web) NOPASSWD: ALL
    validate: /usr/sbin/visudo -csf %s

- name: Surveyor unit
  copy:
    src: surveyor.service
    dest: /etc/systemd/system/
  register: surveyor_unit

- name: Surveyor web unit
  copy:
    src: 'surveyor-web.{{item}}'
    dest: /etc/systemd/system
  loop:
    - service
    - socket
  register: surveyor_web_unit

- name: "Start surveyor systemd unit"
  systemd:
    name: surveyor
    daemon_reload: '{{surveyor_unit.changed}}'
    state: '{{("restarted" if surveyor_unit.changed else "started") if run_surveyor else "stopped"}}'
    enabled: '{{run_surveyor}}'
    masked: false

- name: "Start surveyor-web systemd socket"
  systemd:
    name: surveyor-web.socket
    daemon_reload: '{{surveyor_web_unit.changed}}'
    state: '{{"started" if run_surveyor_web else "stopped"}}'
    enabled: '{{run_surveyor_web}}'
    masked: false

- name: "Stop surveyor-web systemd unit to have it start by socket after update"
  systemd:
    name: surveyor-web.service
    state: stopped
    enabled: false
    masked: false
  when: surveyor_web_unit.changed or surveyor_web_deps_apt.changed or surveyor_web_deps_pip0.changed or surveyor_web_deps_pip1.changed
