#!/bin/bash

echo "🚀 Starting database backup process..."

# Check environment argument
if [ -z "$1" ]; then
  echo "❌ Please provide an environment (e.g., development, staging, production)."
  exit 1
fi

# Set environment file based on argument
ENV_FILE=".env.$1"
if [ ! -f "$ENV_FILE" ]; then
  echo "❌ Environment file $ENV_FILE not found!"
  exit 1
fi

# Clean CRLF line endings from the env file (in case it was edited on Windows)
sed -i 's/\r$//' "$ENV_FILE"

# Load environment variables
set -a
source "$ENV_FILE"
set +a

# Read the tables array (second argument)
TABLES_STRING="$2"

# Clean TABLES_STRING from [ and ] and spaces (handle both "users,orders" and ["users","orders"])
TABLES_STRING_CLEAN=$(echo "$TABLES_STRING" | sed 's/\[//g' | sed 's/\]//g' | sed 's/ //g')

# Convert to array
IFS=',' read -r -a TABLES <<< "$TABLES_STRING_CLEAN"

# Create timestamped folder
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FOLDER="public/backup/${TIMESTAMP}"
mkdir -p "$BACKUP_FOLDER"

# Backup function for specific tables
backup_specific_tables() {
  echo "🔵 Backing up specific tables: ${TABLES[@]}"

  TABLE_LIST=""
  for table in "${TABLES[@]}"; do
    TABLE_LIST+=" -t $table"
  done

  # Capture the output of pg_dump for debugging
  echo "Running pg_dump with the following command:"
  
  PGPASSWORD=$DATABASE_PASSWORD pg_dump -h "$DATABASE_HOST" -p "$DATABASE_PORT" -U "$DATABASE_USER" -d "$DATABASE_NAME" $TABLE_LIST --format=custom --file="$BACKUP_FOLDER/selected_tables_backup.backup" > "$BACKUP_FOLDER/pg_dump_output.log" 2>&1

  # Check if the backup was successful
  if [ $? -eq 0 ]; then
    echo "✅ Backup completed successfully at $BACKUP_FOLDER."
  else
    echo "❌ Backup failed. Check the log file for details: $BACKUP_FOLDER/pg_dump_output.log"
  fi
}

# Backup function for the full database
backup_entire_db() {
  echo "🟢 Backing up the full database..."
  PGPASSWORD=$DATABASE_PASSWORD pg_dump -h "$DATABASE_HOST" -p "$DATABASE_PORT" -U "$DATABASE_USER" -d "$DATABASE_NAME" --format=custom --file="$BACKUP_FOLDER/full_db_backup.backup" > "$BACKUP_FOLDER/pg_dump_output.log" 2>&1
  if [ $? -eq 0 ]; then
    echo "✅ Backup completed successfully at $BACKUP_FOLDER."
  else
    echo "❌ Backup failed. Check the log file for details: $BACKUP_FOLDER/pg_dump_output.log"
  fi
}

# Decision point to determine if we're backing up full DB or specific tables
if [ -z "$TABLES_STRING_CLEAN" ]; then
  backup_entire_db
else
  backup_specific_tables
fi
