#!/bin/bash

# 1. CONFIGURATION
# List folders to exclude (separated by spaces, NOT commas)
EXCLUDED_FOLDERS=("ai" "dns-adguard" "dns-pihole" "immich")

# 2. VALIDATION
# Ensure the script is running as root (Sudo) to avoid permission issues
if [ "$EUID" -ne 0 ]; then
  echo "=========================================="
  echo "ERROR: Please run this script as root"
  echo "Usage: sudo $0"
  echo "=========================================="
  exit 1
fi

# 3. SETUP ABSOLUTE PATHS
# Get the absolute path of the directory where this script is located
# This ensures that even if we 'cd' into folders, we don't lose track of where we are.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "=========================================="
echo "Starting Podman Maintenance Script"
echo "Target Directory: $SCRIPT_DIR"
echo "Excluded Folders: ${EXCLUDED_FOLDERS[*]}"
echo "=========================================="

# 4. MAIN LOOP (Using Globbing instead of 'find' to prevent Subshell issues)
# "$SCRIPT_DIR"/*/ iterates through all immediate subdirectories
for dir in "$SCRIPT_DIR"/*/; do
  # Extract just the folder name (e.g., /podman/essential/ -> "essential")
  folder_name=$(basename "$dir")

  # --- EXCLUSION CHECK ---
  skip_folder=0
  for excluded in "${EXCLUDED_FOLDERS[@]}"; do
    if [[ "$folder_name" == "$excluded" ]]; then
      # Debug: echo "Skipping $folder_name (Excluded)"
      skip_folder=1
      break
    fi
  done
  if [ "$skip_folder" -eq 1 ]; then
    continue
  fi
  # ---------------------

  # Check for compose file (handles both .yml and .yaml)
  COMPOSE_FILE=""
  if [ -f "$dir/docker-compose.yml" ]; then
    COMPOSE_FILE="$dir/docker-compose.yml"
  elif [ -f "$dir/docker-compose.yaml" ]; then
    COMPOSE_FILE="$dir/docker-compose.yaml"
  fi

  # If file exists, proceed with updates
  if [ -n "$COMPOSE_FILE" ]; then
    echo ""
    echo "=========================================="
    echo "[PROCESSING] Folder: $folder_name"

    # Change directory to the stack
    # We trap errors in cd to prevent the script from running commands in the wrong place
    cd "$dir" || {
      echo "[ERROR] Could not enter $dir"
      continue
    }

    echo " -> Step 1: Stopping containers..."
    podman-compose stop

    echo " -> Step 2: Removing containers and networks (Down)..."
    podman-compose down

    echo " -> Step 3: Pulling latest images..."
    podman-compose pull

    echo " -> Step 4: Starting services (Up -d)..."
    podman-compose up -d

    echo " -> [COMPLETED] $folder_name is updated."

    # Return to the base directory (Safety measure)
    cd "$SCRIPT_DIR" || exit
  else
    # Debug: Uncomment the line below to see which folders are being ignored
    # echo "[IGNORE] No compose file in: $folder_name"
    :
  fi
done

echo ""
echo "=========================================="
echo "All tasks successfully completed."
echo "=========================================="
