#!/bin/bash
# Dependency Update Script
# Safely stops services, runs updates, and restarts services
# Designed to be run by systemd timer at scheduled intervals

set -e

LOG_FILE="/opt/media-downloader/logs/dependency-updates.log"
LOCK_FILE="/tmp/dependency-updates.lock"

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') $1" | tee -a "$LOG_FILE"
}

# Check for lock file to prevent concurrent runs
if [ -f "$LOCK_FILE" ]; then
    log "[WARN] Another update process is running. Exiting."
    exit 0
fi

# Create lock file
trap "rm -f $LOCK_FILE" EXIT
echo $$ > "$LOCK_FILE"

log "[INFO] =========================================="
log "[INFO] Starting dependency update process"
log "[INFO] =========================================="

# Check if scheduler is running
SCHEDULER_WAS_RUNNING=false
if systemctl is-active --quiet media-downloader; then
    SCHEDULER_WAS_RUNNING=true
    log "[INFO] Stopping scheduler for updates..."
    systemctl stop media-downloader

    # Wait for clean shutdown
    sleep 5
    log "[INFO] Scheduler stopped"
fi

# Run dependency updates
log "[INFO] Running dependency updates..."
cd /opt/media-downloader

/opt/media-downloader/venv/bin/python3 -c "
import sys
sys.path.insert(0, '/opt/media-downloader')
from modules.dependency_updater import DependencyUpdater
from modules.settings_manager import SettingsManager

# Load config
settings = SettingsManager()
config = settings.get_all()
update_config = config.get('dependency_updater', {}) or config.get('dependency_updates', {})

if not update_config.get('enabled', True):
    print('[INFO] Dependency updates disabled in config')
    sys.exit(0)

updater = DependencyUpdater(config=update_config, scheduler_mode=True)
results = updater.force_update_check()

print('[INFO] Update results:')
for component, updated in results.items():
    status = 'Updated' if updated else 'Current'
    print(f'  - {component}: {status}')
" 2>&1 | tee -a "$LOG_FILE"

UPDATE_STATUS=$?

if [ $UPDATE_STATUS -eq 0 ]; then
    log "[INFO] Dependency updates completed successfully"
else
    log "[ERROR] Dependency updates failed with status $UPDATE_STATUS"
fi

# Restart API to pick up any Python package changes
log "[INFO] Restarting API service..."
systemctl restart media-downloader-api
sleep 2

if systemctl is-active --quiet media-downloader-api; then
    log "[INFO] API service restarted successfully"
else
    log "[ERROR] API service failed to restart!"
fi

# Restart scheduler if it was running
if [ "$SCHEDULER_WAS_RUNNING" = true ]; then
    log "[INFO] Restarting scheduler..."
    systemctl start media-downloader
    sleep 3

    if systemctl is-active --quiet media-downloader; then
        log "[INFO] Scheduler restarted successfully"
    else
        log "[ERROR] Scheduler failed to restart!"
    fi
fi

log "[INFO] =========================================="
log "[INFO] Dependency update process complete"
log "[INFO] =========================================="
