---
# PostgreSQL Database Setup via Docker

- name: Create PostgreSQL data directory
  file:
    path: /var/lib/postgresql/data
    state: directory
    mode: '0755'

- name: Create PostgreSQL backup directory
  file:
    path: /var/backups/postgresql
    state: directory
    mode: '0755'

- name: Deploy PostgreSQL container
  docker_container:
    name: postgres
    image: postgres:{{ postgres_version }}
    state: started
    restart_policy: always
    networks:
      - name: undateable-net
    ports:
      - "5432:5432"
    volumes:
      - /var/lib/postgresql/data:/var/lib/postgresql/data
    env:
      POSTGRES_DB: "{{ postgres_db }}"
      POSTGRES_USER: "{{ postgres_user }}"
      POSTGRES_PASSWORD: "{{ postgres_password }}"
      PGDATA: /var/lib/postgresql/data/pgdata
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U {{ postgres_user }}"]
      interval: 10s
      timeout: 5s
      retries: 5

- name: Wait for PostgreSQL to be ready
  wait_for:
    port: 5432
    delay: 5
    timeout: 60

- name: Create daily backup cron job
  cron:
    name: "PostgreSQL daily backup"
    hour: "2"
    minute: "0"
    job: "docker exec postgres pg_dump -U {{ postgres_user }} {{ postgres_db }} | gzip > /var/backups/postgresql/backup_$(date +\\%Y\\%m\\%d).sql.gz"
    user: root

- name: Create backup cleanup cron job (keep 7 days)
  cron:
    name: "Cleanup old PostgreSQL backups"
    hour: "3"
    minute: "0"
    job: "find /var/backups/postgresql -name '*.sql.gz' -mtime +7 -delete"
    user: root
