#!/bin/bash
set -euo pipefail

# --- Default configuration ---
PG_USER="postgres"
PG_DB="your_database"
PG_HOST="localhost"
PG_PORT="5432"
BACKUP_DIR="/media/backup/kot"
RETENTION_DAYS=7

# --- Usage/help function ---
usage() {
  cat <<EOF
Usage: $0 [OPTIONS]

Options (all are optional; defaults shown):
  --user         Postgres user         (default: $PG_USER)
  --db           Database name         (default: $PG_DB)
  --host         Postgres host         (default: $PG_HOST)
  --port         Postgres port         (default: $PG_PORT)
  --backup-dir   Backup directory      (default: $BACKUP_DIR)
  --retention    Retention (days)      (default: $RETENTION_DAYS)
  --help         Show this help

Notes:
- Passwordless login uses ~/.pgpass (see script comments).
- Old backups older than retention will be deleted automatically.
EOF
}

# --- Parse named arguments ---
while [[ $# -gt 0 ]]; do
  case "$1" in
    --user)       PG_USER="$2"; shift 2;;
    --db)         PG_DB="$2"; shift 2;;
    --host)       PG_HOST="$2"; shift 2;;
    --port)       PG_PORT="$2"; shift 2;;
    --backup-dir) BACKUP_DIR="$2"; shift 2;;
    --retention)  RETENTION_DAYS="$2"; shift 2;;
    --help)       usage; exit 0;;
    *) echo "Unknown option: $1"; usage; exit 1;;
  esac
done

# --- .pgpass usage info ---
# Make sure ~/.pgpass contains:
# hostname:port:database:username:password
# Example:
# localhost:5432:your_database:postgres:your_password
# Permissions: chmod 600 ~/.pgpass

# --- Timestamp and backup filename ---
NOW=$(date +"%Y-%m-%d_%H-%M-%S")
BACKUP_FILE="${BACKUP_DIR}/${PG_DB}_backup_${NOW}.sql.gz"

# --- Ensure backup dir exists ---
mkdir -p "$BACKUP_DIR"

# --- Run backup ---
pg_dump -U "$PG_USER" -h "$PG_HOST" -p "$PG_PORT" "$PG_DB" | gzip > "$BACKUP_FILE"

if [ $? -eq 0 ]; then
    echo "✅ Backup successful: $BACKUP_FILE"
else
    echo "❌ Backup failed!" >&2
    exit 1
fi

# --- Cleanup old backups (optional) ---
find "$BACKUP_DIR" -name "${PG_DB}_backup_*.sql.gz" -mtime +$RETENTION_DAYS -delete

exit 0