#!/bin/bash
set -Eeuo pipefail

# Configuration
SOURCE_ENV="${1:-dbdev}"
DBNAME="${2:-geco}"
POD_NAME="${3:-postgresql-1-postgresql-0}"
CONTAINER_NAME="${4:-postgresql-server}"
BACKUP_REMOTE_DIR="${5:-/shared/backup}"
BACKUP_LOCAL_DIR="${6:-.}"
COMPRESSION="${7:-true}"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Logging function
log() {
  echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $*"
}

error() {
  echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR:${NC} $*" >&2
  exit 1
}

warn() {
  echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARN:${NC} $*"
}

# Determine backup file extension
if [ "${COMPRESSION}" = "true" ]; then
  BACKUP_FILE="${DBNAME}-${SOURCE_ENV}-$(date +%Y%m%d-%H%M%S).backup.gz"
  DUMP_FORMAT="c"
else
  BACKUP_FILE="${DBNAME}-${SOURCE_ENV}-$(date +%Y%m%d-%H%M%S).backup"
  DUMP_FORMAT="c"
fi

log "Inizio backup database PostgreSQL"
log "Namespace: ${SOURCE_ENV}"
log "Pod: ${POD_NAME}"
log "Database: ${DBNAME}"
log "File di backup: ${BACKUP_FILE}"

# Check if namespace exists
if ! kubectl get namespace "${SOURCE_ENV}" &>/dev/null; then
  error "Namespace '${SOURCE_ENV}' non trovato"
fi

# Check if pod exists
if ! kubectl get pod "${POD_NAME}" -n "${SOURCE_ENV}" &>/dev/null; then
  error "Pod '${POD_NAME}' non trovato nel namespace '${SOURCE_ENV}'"
fi

# Check if pod is running
POD_STATUS=$(kubectl get pod "${POD_NAME}" -n "${SOURCE_ENV}" -o jsonpath='{.status.phase}')
if [ "${POD_STATUS}" != "Running" ]; then
  error "Pod '${POD_NAME}' non è in stato Running (stato attuale: ${POD_STATUS})"
fi

log "Creazione backup sul pod..."

# Create backup on remote pod
if [ "${COMPRESSION}" = "true" ]; then
  kubectl exec -i "${POD_NAME}" \
    -c "${CONTAINER_NAME}" \
    -n "${SOURCE_ENV}" \
    -- pg_dump -U postgres -d "${DBNAME}" -F "${DUMP_FORMAT}" -b -v | gzip > "${BACKUP_LOCAL_DIR}/${BACKUP_FILE}" || error "Backup fallito"
else
  kubectl exec -i "${POD_NAME}" \
    -c "${CONTAINER_NAME}" \
    -n "${SOURCE_ENV}" \
    -- pg_dump -U postgres -d "${DBNAME}" -F "${DUMP_FORMAT}" -b -v > "${BACKUP_LOCAL_DIR}/${BACKUP_FILE}" || error "Backup fallito"
fi

log "Backup completato"

# Verify file exists and has content
if [ ! -f "${BACKUP_LOCAL_DIR}/${BACKUP_FILE}" ]; then
  error "File di backup non trovato: ${BACKUP_LOCAL_DIR}/${BACKUP_FILE}"
fi

FILE_SIZE=$(du -h "${BACKUP_LOCAL_DIR}/${BACKUP_FILE}" | cut -f1)
if [ -z "${FILE_SIZE}" ] || [ "${FILE_SIZE}" = "0" ]; then
  error "File di backup vuoto o non valido"
fi

log "✅ Backup completato con successo"
log "Percorso: ${BACKUP_LOCAL_DIR}/${BACKUP_FILE}"
log "Dimensione: ${FILE_SIZE}"

log "Inizio trasferimento file di backup su server remoto..."
if sshpass -p "POC-25_sts" scp "${BACKUP_LOCAL_DIR}/${BACKUP_FILE}" barucci@10.20.1.101:/home/barucci/froms/; then
  log "✅ File trasferito con successo su 10.20.1.101"
  log "Destinazione: barucci@10.20.1.101:/home/barucci/froms/${BACKUP_FILE}"
else
  warn "Trasferimento file fallito, ma backup locale è disponibile in ${BACKUP_LOCAL_DIR}/${BACKUP_FILE}"
fi