#!/bin/bash

# Nextcloud Maintenance Script.
# This script performs maintenance tasks for Nextcloud.

set -e

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

CONTAINER_NAME="nextcloud"

# Function to print colored messages.
printMessage() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# Function to run occ command.
runOcc() {
    docker exec -u www-data "$CONTAINER_NAME" php occ "$@"
}

# Load environment variables.
loadEnv() {
  if [ -f "./nextcloud/.env" ]; then
    source ./nextcloud/.env
    printMessage "$GREEN" "Loaded Nextcloud environment variables."
  else
    printMessage "$RED" "Nextcloud .env file not found!"
    exit 1
  fi

  if [ -f "./core/.env" ]; then
    source ./core/.env
    printMessage "$GREEN" "Loaded core environment variables."
  else
    printMessage "$RED" "Core .env file not found!"
    exit 1
  fi
}

# Function to check if container is running.
checkContainer() {
  if ! docker ps | grep -q "$CONTAINER_NAME"; then
    printMessage "$RED" "Error: Container $CONTAINER_NAME is not running!"
    exit 1
  fi
}

# Function to fix database collation version mismatch.
fix_database_collation() {
  printMessage "$YELLOW" "Checking and fixing database collation version..."
  
  if docker exec postgres psql -U "${POSTGRES_USER}" -d "${NEXTCLOUD_DB_NAME}" -c "ALTER DATABASE ${NEXTCLOUD_DB_NAME} REFRESH COLLATION VERSION;" 2>&1 | grep -q "ALTER DATABASE"; then
    printMessage "$GREEN" "Database collation version updated successfully."
    return 0
  else
    printMessage "$YELLOW" "Database collation check completed (may already be up to date)."
    return 0
  fi
}

# Function to check Nextcloud status.
check_status() {
  printMessage "$YELLOW" "Checking Nextcloud status..."
  runOcc status
  return 0
}

# Function to scan files.
scan_files() {
  if [ -z "$1" ]; then
    printMessage "$YELLOW" "Scanning all files..."
    runOcc files:scan --all
  else
    printMessage "$YELLOW" "Scanning files for user: $1..."
    runOcc files:scan "$1"
  fi
  return 0
}

# Function to update Nextcloud.
update_nextcloud() {
  printMessage "$YELLOW" "Running database upgrade..."
  runOcc upgrade
  return 0
}

# Function to optimize database.
optimize_database() {
  printMessage "$YELLOW" "Optimizing database..."
  runOcc db:add-missing-indices
  runOcc db:add-missing-columns
  runOcc db:add-missing-primary-keys
  return 0
}

# Function to run maintenance repair.
run_repair() {
  printMessage "$YELLOW" "Running maintenance repair..."
  runOcc maintenance:repair
  return 0
}

# Function to run comprehensive post-update maintenance.
post_update_maintenance() {
  checkContainer
  
  printMessage "$GREEN" "========================================="
  printMessage "$GREEN" "Nextcloud Post-Update Maintenance"
  printMessage "$GREEN" "========================================="
  echo ""

  printMessage "$YELLOW" "[1/10] Enabling maintenance mode..."
  runOcc maintenance:mode --on

  printMessage "$YELLOW" "[2/10] Running database upgrade..."
  runOcc upgrade

  printMessage "$YELLOW" "[3/10] Adding missing database indices..."
  runOcc db:add-missing-indices

  printMessage "$YELLOW" "[4/10] Adding missing database columns..."
  runOcc db:add-missing-columns

  printMessage "$YELLOW" "[5/10] Adding missing primary keys..."
  runOcc db:add-missing-primary-keys

  printMessage "$YELLOW" "[6/10] Converting filecache to big int (if needed)..."
  runOcc db:convert-filecache-bigint --no-interaction || printMessage "$YELLOW" "Already converted or not needed."

  printMessage "$YELLOW" "[7/10] Updating .htaccess and configuration files..."
  runOcc maintenance:update:htaccess

  printMessage "$YELLOW" "[8/10] Updating theme..."
  runOcc maintenance:theme:update

  printMessage "$YELLOW" "[9/10] Running repair steps..."
  runOcc maintenance:repair

  printMessage "$YELLOW" "[10/10] Disabling maintenance mode..."
  runOcc maintenance:mode --off

  echo ""
  printMessage "$GREEN" "========================================="
  printMessage "$GREEN" "Maintenance completed successfully!"
  printMessage "$GREEN" "========================================="
  echo ""

  printMessage "$YELLOW" "System Status:"
  runOcc status

  echo ""
  printMessage "$GREEN" "You may want to run background jobs manually:"
  printMessage "$YELLOW" "  docker exec -u www-data $CONTAINER_NAME php occ background:job:execute"
}

# Main execution.
printMessage "$YELLOW" "Running Nextcloud maintenance tasks..."

case "${1:-all}" in
  collation)
    loadEnv
    checkContainer
    fix_database_collation
    ;;
  status)
    checkContainer
    check_status
    ;;
  scan)
    checkContainer
    scan_files "$2"
    ;;
  update)
    checkContainer
    update_nextcloud
    ;;
  optimize)
    checkContainer
    optimize_database
    ;;
  repair)
    checkContainer
    run_repair
    ;;
  post-update)
    loadEnv
    post_update_maintenance
    ;;
  all)
    loadEnv
    checkContainer
    fix_database_collation
    echo ""
    check_status
    echo ""
    optimize_database
    echo ""
    run_repair
    echo ""
    printMessage "$YELLOW" "Disabling maintenance mode..."
    runOcc maintenance:mode --off
    echo ""
    printMessage "$GREEN" "All maintenance tasks completed."
    ;;
  *)
    echo "Usage: $0 [collation|status|scan|update|optimize|repair|post-update|all]"
    echo ""
    echo "Commands:"
    echo "  collation   - Fix database collation version mismatch"
    echo "  status      - Check Nextcloud status"
    echo "  scan        - Scan files (optionally specify username)"
    echo "  update      - Update Nextcloud database"
    echo "  optimize    - Optimize database indices and columns"
    echo "  repair      - Run maintenance repair"
    echo "  post-update - Run comprehensive post-update maintenance workflow"
    echo "  all         - Run all basic maintenance tasks (default)"
    exit 1
    ;;
esac
