- name: "Install pg_cron extension postgresql-{{ postgresql_version }}-cron"
  tags:
    - install
    - timescaledb_install
  apt:
    pkg:
      - "postgresql-{{ postgresql_version }}-cron"
    state: latest
    update_cache: yes

- name: "Stop postgresql service"
  tags:
    - install
    - timescaledb_install
  systemd:
    name: postgresql
    state: stopped

- name: "Add pg_cron to shared_preload_libraries"
  tags:
    - install
    - timescaledb_install    
  lineinfile:
    path: /etc/postgresql/{{ postgresql_version }}/main/postgresql.conf
    regexp: "^shared_preload_libraries = 'timescaledb'"
    line: "shared_preload_libraries = 'timescaledb,pg_cron'"

- name: "Define cron database name"
  tags:
    - install
    - timescaledb_install    
  lineinfile:
    dest: /etc/postgresql/{{ postgresql_version }}/main/postgresql.conf
    line: "cron.database_name = '{{ timescaledb_database_name }}'"

- name: "Define cron timezone"
  tags:
    - install
    - timescaledb_install    
  lineinfile:
    dest: /etc/postgresql/{{ postgresql_version }}/main/postgresql.conf
    line: "cron.timezone = 'Europe/Berlin'"

- name: "Start postgresql service"
  tags:
    - install
    - timescaledb_install
  systemd:
    name: postgresql
    state: started

- name: "Create pg_cron functions on database {{ timescaledb_database_name }}"
  tags:
    - install
    - timescaledb_install
  postgresql_ext:
    name: pg_cron
    db: "{{ timescaledb_database_name }}"
    state: present
    login_user: "postgres"
    login_password: "{{ postgresql_admin_password }}"
    login_host: "{{ lxc_ip }}"

- name: "Grant privilege USAGE to schema cron for user {{ timescaledb_database_user }}"
  tags:
    - install
    - timescaledb_install
  postgresql_privs:
    db: "{{ timescaledb_database_name }}"
    privs: USAGE
    type: schema
    obj: "cron"
    role: "{{ timescaledb_database_user }}"
    login_user: "postgres"
    login_password: "{{ postgresql_admin_password }}"
    login_host: "{{ lxc_ip }}"