#!/bin/bash

# Media Downloader Uninstaller Script
# Version: 11.27.0

set -e

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

# Installation directory
INSTALL_DIR="/opt/media-downloader"

echo -e "${RED}╔════════════════════════════════════════════════╗${NC}"
echo -e "${RED}║   Media Downloader Uninstaller                 ║${NC}"
echo -e "${RED}╚════════════════════════════════════════════════╝${NC}"
echo ""

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}This script must be run as root (use sudo)${NC}"
   exit 1
fi

echo -e "${YELLOW}This will remove:${NC}"
echo "  - Installation directory: $INSTALL_DIR"
echo "  - All systemd services and timers"
echo "  - Command wrapper: /usr/local/bin/media-downloader"
echo ""
echo -e "${YELLOW}Services to be removed:${NC}"
echo "  - media-downloader (scheduler)"
echo "  - media-downloader-api (web API)"
echo "  - media-downloader-frontend (web UI)"
echo "  - xvfb-media-downloader (virtual display)"
echo "  - media-cache-builder (timer)"
echo "  - media-embedding-generator (timer)"
echo "  - media-celebrity-enrichment (timer)"
echo ""
echo -e "${YELLOW}This will NOT remove:${NC}"
echo "  - Downloaded media files (if stored elsewhere)"
echo "  - Python packages installed system-wide"
echo "  - Redis server"
echo "  - FlareSolverr Docker container"
echo ""

read -p "Continue with uninstallation? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Uninstallation cancelled"
    exit 1
fi

# ============================================================================
# STOP ALL SERVICES
# ============================================================================

echo -e "${YELLOW}Stopping all services...${NC}"

# Stop main services
for service in media-downloader media-downloader-api media-downloader-frontend xvfb-media-downloader; do
    if systemctl is-active --quiet $service 2>/dev/null; then
        echo "  Stopping $service..."
        systemctl stop $service
    fi
done

# Stop timers
for timer in media-cache-builder media-embedding-generator media-celebrity-enrichment; do
    if systemctl is-active --quiet $timer.timer 2>/dev/null; then
        echo "  Stopping $timer.timer..."
        systemctl stop $timer.timer
    fi
done

# ============================================================================
# DISABLE SERVICES
# ============================================================================

echo -e "${YELLOW}Disabling services...${NC}"

# Disable main services
for service in media-downloader media-downloader-api media-downloader-frontend xvfb-media-downloader; do
    if systemctl is-enabled --quiet $service 2>/dev/null; then
        echo "  Disabling $service..."
        systemctl disable $service
    fi
done

# Disable timers
for timer in media-cache-builder media-embedding-generator media-celebrity-enrichment; do
    if systemctl is-enabled --quiet $timer.timer 2>/dev/null; then
        echo "  Disabling $timer.timer..."
        systemctl disable $timer.timer
    fi
done

# ============================================================================
# REMOVE SYSTEMD FILES
# ============================================================================

echo -e "${YELLOW}Removing systemd files...${NC}"

rm -f /etc/systemd/system/media-downloader.service
rm -f /etc/systemd/system/media-downloader-api.service
rm -f /etc/systemd/system/media-downloader-frontend.service
rm -f /etc/systemd/system/xvfb-media-downloader.service
rm -f /etc/systemd/system/media-cache-builder.service
rm -f /etc/systemd/system/media-cache-builder.timer
rm -f /etc/systemd/system/media-embedding-generator.service
rm -f /etc/systemd/system/media-embedding-generator.timer
rm -f /etc/systemd/system/media-celebrity-enrichment.service
rm -f /etc/systemd/system/media-celebrity-enrichment.timer

# Reload systemd
systemctl daemon-reload

# ============================================================================
# BACKUP DATA
# ============================================================================

if [ -d "$INSTALL_DIR" ]; then
    BACKUP_DIR="$HOME/media-downloader-backup-$(date +%Y%m%d-%H%M%S)"
    echo -e "${GREEN}Creating backup at $BACKUP_DIR${NC}"
    mkdir -p "$BACKUP_DIR"

    # Backup config directory
    if [ -d "$INSTALL_DIR/config" ]; then
        cp -r "$INSTALL_DIR/config" "$BACKUP_DIR/"
        echo "  ✓ Configuration directory backed up"
    fi

    # Backup sessions
    if [ -d "$INSTALL_DIR/sessions" ]; then
        cp -r "$INSTALL_DIR/sessions" "$BACKUP_DIR/"
        echo "  ✓ Sessions backed up"
    fi

    # Backup cookies
    if [ -d "$INSTALL_DIR/cookies" ]; then
        cp -r "$INSTALL_DIR/cookies" "$BACKUP_DIR/"
        echo "  ✓ Forum cookies backed up"
    fi

    # Backup database directory
    if [ -d "$INSTALL_DIR/database" ]; then
        cp -r "$INSTALL_DIR/database" "$BACKUP_DIR/"
        echo "  ✓ Database directory backed up"
    fi

    # Backup data directory
    if [ -d "$INSTALL_DIR/data" ]; then
        cp -r "$INSTALL_DIR/data" "$BACKUP_DIR/"
        echo "  ✓ Data directory backed up"
    fi
fi

# ============================================================================
# REMOVE INSTALLATION
# ============================================================================

# Remove installation directory
if [ -d "$INSTALL_DIR" ]; then
    echo -e "${YELLOW}Removing installation directory...${NC}"
    rm -rf "$INSTALL_DIR"
fi

# Remove command wrapper
if [ -f "/usr/local/bin/media-downloader" ]; then
    echo -e "${YELLOW}Removing command wrapper...${NC}"
    rm -f "/usr/local/bin/media-downloader"
fi

# ============================================================================
# COMPLETION
# ============================================================================

echo ""
echo -e "${GREEN}╔════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║      Uninstallation Complete!                  ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════╝${NC}"
echo ""

if [ -n "$BACKUP_DIR" ] && [ -d "$BACKUP_DIR" ]; then
    echo -e "${BLUE}Backup created at:${NC} $BACKUP_DIR"
    echo ""
    echo -e "${YELLOW}To restore your data to a new installation:${NC}"
    echo "  1. Install Media Downloader again:"
    echo "     sudo ./scripts/install.sh"
    echo ""
    echo "  2. Restore your backed up data:"
    echo "     sudo cp -r $BACKUP_DIR/database/* /opt/media-downloader/database/"
    echo "     sudo cp -r $BACKUP_DIR/config/* /opt/media-downloader/config/"
    echo "     sudo cp -r $BACKUP_DIR/sessions /opt/media-downloader/"
    echo "     sudo cp -r $BACKUP_DIR/cookies /opt/media-downloader/"
    echo "     sudo cp -r $BACKUP_DIR/data/* /opt/media-downloader/data/"
    echo "     sudo chown -R \$USER:\$USER /opt/media-downloader/"
    echo ""
    echo "  3. Restart the services:"
    echo "     sudo systemctl restart media-downloader"
    echo "     sudo systemctl restart media-downloader-api"
fi
