---
# Configuration for repoSpanner server

- name: install needed packages
  package: name={{ item }} state=present
  with_items:
  - repoSpanner
  tags:
  - repospanner/server
  - packages

- name: ensure needed directories
  file:
    path: "{{ item }}"
    state: directory
    owner: root
    group: root
    mode: 0755
  with_items:
    - /etc/repospanner/
    - /etc/pki/repospanner/
    - /var/lib/repospanner/
  tags:
  - repospanner/server

- name: Create group
  group:
    name: repoSpanner
    state: present
  tags:
  - repospanner/server
  - config

- name: Create user
  user:
    name: repoSpanner
    state: present
    group: repoSpanner
    shell: /sbin/nologin
  tags:
  - repospanner/server
  - config

- name: Create instance directory
  file:
    path: /var/lib/repospanner/{{region}}
    state: directory
    owner: repoSpanner
    group: repoSpanner
    mode: 0755
  tags:
  - repospanner/server

- name: Deploy configuration
  template: src=repoSpanner.yml
            dest=/etc/repospanner/{{region}}-config.yml
            owner=repoSpanner group=repoSpanner mode=0600
  register: repospanner_refresh
  tags:
  - repospanner/server
  - config

- name: Deploy certificates
  copy: src="{{private}}/files/repoSpanner/{{env}}/ca/{{item.src}}"
        dest="/etc/repospanner/{{item.dest}}"
        owner=repoSpanner group=repoSpanner mode=0600
  with_items:
  - src: ca.crt
    dest: ca.crt
  - src: "{{node}}.{{region}}.crt"
    dest: node-{{region}}.crt
  - src: "{{node}}.{{region}}.key"
    dest: node-{{region}}.key
  register: repospanner_refresh
  tags:
  - repospanner/server
  - config

- name: Deploy unit file
  template: src=repoSpanner.service
            dest=/etc/systemd/system/repoSpanner@{{ region }}.service
  register: repospanner_systemd
  tags:
  - repospanner/server
  - config

- name: Spawn node
  command: repospanner --config /etc/repospanner/{{region}}-config.yml serve --spawn
  args:
    creates: /var/lib/repospanner/{{region}}state/state.json
  become: yes
  become_user: repoSpanner
  when: "spawn_repospanner_node is defined and spawn_repospanner_node == true"
  tags:
  - repospanner/server
  - config

- name: Join node
  command: repospanner --config /etc/repospanner/{{region}}-config.yml serve --joinnode https://{{ join_repospanner_node }}:{{ rpc_port }}
  args:
    creates: /var/lib/repospanner/{{region}}state/state.json
  become: yes
  become_user: repoSpanner
  when: "spawn_repospanner_node is not defined or spawn_repospanner_node == false"
  tags:
  - repospanner/server
  - config

- name: Start and enable
  service: name=repoSpanner@{{ region }} state=started enabled=yes
  tags:
  - repospanner/server
  - config

- name: Reload systemd when needed
  shell: /usr/bin/systemctl daemon-reload
  when: repospanner_systemd is changed
  tags:
    - systemd

- name: Restart service when needed
  service:
    name: "repoSpanner@{{ region }}"
    state: restarted
  when: repospanner_refresh is changed
