---

- name: install keycloak
  pacman: name=jre11-openjdk,keycloak,keycloak-metrics-spi,python-passlib state=present

- name: template keycloak config
  template: src=standalone.xml.j2 dest=/etc/keycloak/standalone.xml owner=keycloak group=keycloak mode=600
  notify:
    - restart keycloak

- name: copy custom theme
  copy: src=theme/archlinux dest=/opt/keycloak/themes owner=keycloak group=keycloak mode=755
  notify:
    - restart keycloak

- name: request a bearer token
  uri:
    url: http://127.0.0.1:8080/auth/realms/master/protocol/openid-connect/token
    method: POST
    body_format: form-urlencoded
    body:
      username: "{{ vault_keycloak_admin_user }}"
      password: "{{ vault_keycloak_admin_password }}"
      grant_type: password
      client_id: admin-cli
  ignore_errors: true
  register: token

- name: create an admin user
  command: /opt/keycloak/bin/add-user-keycloak.sh -r master -u "{{ vault_keycloak_admin_user }}" -p "{{ vault_keycloak_admin_password }}"
  when: token.status == 401

- name: start and enable keycloak
  service: name=keycloak enabled=yes state=started

- name: open firewall hole
  ansible.posix.firewalld: port={{ item }} permanent=true state=enabled immediate=yes
  when: configure_firewall
  with_items:
    - 80/tcp
    - 443/tcp
  tags:
    - firewall

- name: create postgres keycloak user
  postgresql_user: name="{{ vault_keycloak_db_user }}" password="{{ vault_keycloak_db_password }}"
  become: true
  become_user: postgres
  become_method: su
  no_log: true

- name: create keycloak db
  postgresql_db: name=keycloak owner="{{ vault_keycloak_db_user }}"
  become: true
  become_user: postgres
  become_method: su

- name: create htpasswd for nginx prometheus endpoint
  htpasswd:
    path: "{{ keycloak_nginx_htpasswd }}"
    name: "{{ vault_keycloak_nginx_user }}"
    password: "{{ vault_keycloak_nginx_passwd }}"
    owner: root
    group: http
    mode: 0640

- name: create ssl cert
  include_role:
    name: certificate
  vars:
    domains: ["{{ keycloak_domain }}"]

- name: make nginx log dir
  file: path="/var/log/nginx/{{ keycloak_domain }}" state=directory owner=root mode=0755

- name: set up nginx
  template: src=nginx.d.conf.j2 dest=/etc/nginx/nginx.d/keycloak.conf owner=root group=root mode=0644
  notify:
    - reload nginx
  tags: ['nginx']
