#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

---
- name: Install postgresql and postgresql-contrib
  apt:
    name:
      - postgresql-14
      - postgresql-contrib-14
  become: yes

- name: "Install Python packages"
  apt:
    name: "{{ item }}"
    state: present
  with_items:
    - python3-psycopg2
  become: yes

- name: Start the postgresql service
  service:
    name: postgresql
    state: started
    enabled: yes
  become: yes

- name: "Create database"
  postgresql_db:
    state: present
    name: "{{ keycloak_db_schema_name }}"
    login_password: "{{ keycloak_db_password }}"
  become: yes
  become_user: postgres

- name: "Create db user"
  postgresql_user:
    state: present
    name: "{{ keycloak_db_username }}"
    password: "{{ keycloak_db_password }}"
    login_password: "{{ keycloak_db_password }}"
  become: yes
  become_user: postgres

- name: "Grant db user access to app db"
  postgresql_privs:
    type: database
    database: "{{ keycloak_db_schema_name }}"
    roles: "{{ keycloak_db_username }}"
    grant_option: no
    privs: all
    login_password: "{{ keycloak_db_password }}"
  become: yes
  become_user: postgres

- name: copy postgres hba conf
  template:
    src: pg_hba.conf.j2
    dest: /etc/postgresql/14/main/pg_hba.conf
    owner: root
    group: root
    mode: '0644'
  become: yes

- name: Restart the postgresql service
  service:
    name: postgresql
    state: restarted
  become: yes