#!/bin/bash

# Stoatchat Restore Script
# Restores a complete backup of the Stoatchat instance

set -e  # Exit on any error

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

log() {
    echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

success() {
    echo -e "${GREEN}✅ $1${NC}"
}

warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

error() {
    echo -e "${RED}❌ $1${NC}"
    exit 1
}

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   error "This script must be run as root"
fi

# Check if backup path provided
if [ $# -eq 0 ]; then
    error "Usage: $0 <backup-directory-name>"
fi

BACKUP_NAME="$1"
BACKUP_DIR="/root/stoatchat-backups"
BACKUP_PATH="${BACKUP_DIR}/${BACKUP_NAME}"
STOATCHAT_DIR="/root/stoatchat"

# Check if backup exists
if [ ! -d "${BACKUP_PATH}" ]; then
    # Try to extract from tar.gz
    if [ -f "${BACKUP_PATH}.tar.gz" ]; then
        log "Extracting backup archive..."
        cd "${BACKUP_DIR}"
        tar -xzf "${BACKUP_NAME}.tar.gz"
        success "Backup archive extracted"
    else
        error "Backup not found: ${BACKUP_PATH} or ${BACKUP_PATH}.tar.gz"
    fi
fi

log "Starting Stoatchat restore process..."
log "Restoring from: ${BACKUP_PATH}"

# Stop services before restore
log "Stopping Stoatchat services..."
pkill -f revolt || true
docker-compose -f "${STOATCHAT_DIR}/compose.yml" down 2>/dev/null || true
systemctl stop nginx 2>/dev/null || true
success "Services stopped"

# 1. Restore Configuration Files
log "Restoring configuration files..."
if [ -d "${BACKUP_PATH}/config" ]; then
    cp "${BACKUP_PATH}/config/"* "${STOATCHAT_DIR}/" 2>/dev/null || warning "Some config files could not be restored"
    success "Configuration files restored"
else
    warning "No configuration backup found"
fi

# 2. Restore Nginx Configuration
log "Restoring Nginx configuration..."
if [ -d "${BACKUP_PATH}/nginx" ]; then
    mkdir -p /etc/nginx/sites-available
    mkdir -p /etc/nginx/ssl
    cp -r "${BACKUP_PATH}/nginx/st.vish.gg" /etc/nginx/sites-available/ 2>/dev/null || warning "Nginx site config not restored"
    cp -r "${BACKUP_PATH}/nginx/ssl/"* /etc/nginx/ssl/ 2>/dev/null || warning "SSL certificates not restored"

    # Enable site
    ln -sf /etc/nginx/sites-available/st.vish.gg /etc/nginx/sites-enabled/ 2>/dev/null || true
    success "Nginx configuration restored"
else
    warning "No Nginx backup found"
fi

# 3. Restore MongoDB Database
log "Restoring MongoDB database..."
if [ -d "${BACKUP_PATH}/mongodb" ]; then
    # Start MongoDB if not running
    systemctl start mongod 2>/dev/null || docker-compose -f "${STOATCHAT_DIR}/compose.yml" up -d mongo 2>/dev/null || true
    sleep 5

    if command -v mongorestore &> /dev/null; then
        mongorestore --host localhost:27017 --db revolt --drop "${BACKUP_PATH}/mongodb/revolt"
        success "MongoDB database restored"
    else
        # Use docker if mongorestore not available
        if docker ps | grep -q mongo; then
            docker cp "${BACKUP_PATH}/mongodb" $(docker ps --format "table {{.Names}}" | grep mongo | head -1):/tmp/
            docker exec $(docker ps --format "table {{.Names}}" | grep mongo | head -1) mongorestore --db revolt --drop /tmp/mongodb/revolt
            success "MongoDB database restored (via Docker)"
        else
            warning "MongoDB restore skipped - no mongorestore or mongo container found"
        fi
    fi
else
    warning "No MongoDB backup found"
fi

# 4. Restore User Uploads and Files
log "Restoring user uploads and file storage..."
if [ -d "${BACKUP_PATH}/files" ]; then
    mkdir -p "${STOATCHAT_DIR}/uploads"
    cp -r "${BACKUP_PATH}/files/"* "${STOATCHAT_DIR}/" 2>/dev/null || warning "Some files could not be restored"
    success "User files restored"
else
    warning "No file backup found"
fi

# 5. Restore Docker Volumes
log "Restoring Docker volumes..."
if [ -d "${BACKUP_PATH}/docker-volumes" ]; then
    for volume_backup in "${BACKUP_PATH}/docker-volumes"/*.tar.gz; do
        if [ -f "$volume_backup" ]; then
            volume_name=$(basename "$volume_backup" .tar.gz)
            log "Restoring volume: $volume_name"

            # Create volume if it doesn't exist
            docker volume create "$volume_name" 2>/dev/null || true

            # Restore volume data
            docker run --rm -v "$volume_name":/target -v "${BACKUP_PATH}/docker-volumes":/backup alpine tar xzf "/backup/${volume_name}.tar.gz" -C /target
        fi
    done
    success "Docker volumes restored"
else
    warning "No Docker volume backups found"
fi

# 6. Set proper permissions
log "Setting proper permissions..."
chown -R root:root "${STOATCHAT_DIR}"
chmod +x "${STOATCHAT_DIR}/manage-services.sh" 2>/dev/null || true
chmod +x "${STOATCHAT_DIR}/backup.sh" 2>/dev/null || true
chmod +x "${STOATCHAT_DIR}/restore.sh" 2>/dev/null || true
success "Permissions set"

# 7. Start services
log "Starting services..."
systemctl start nginx 2>/dev/null || warning "Could not start nginx"
cd "${STOATCHAT_DIR}"
docker-compose up -d 2>/dev/null || warning "Could not start Docker services"

# Start Stoatchat services
if [ -f "${STOATCHAT_DIR}/manage-services.sh" ]; then
    "${STOATCHAT_DIR}/manage-services.sh" start 2>/dev/null || warning "Could not start Stoatchat services with manage-services.sh"
else
    # Manual start
    REVOLT_CONFIG_PATH=Revolt.overrides.toml nohup "${STOATCHAT_DIR}/target/debug/revolt-delta" > api.log 2>&1 &
    warning "Started services manually - consider using manage-services.sh"
fi

success "Services started"

# 8. Verify restoration
log "Verifying restoration..."
sleep 10

# Check if API is responding
if curl -s http://localhost:14702/health >/dev/null 2>&1; then
    success "API service is responding"
else
    warning "API service may not be fully started yet"
fi

# Check if nginx is serving the site
if curl -s -k https://localhost >/dev/null 2>&1; then
    success "Nginx is serving HTTPS"
else
    warning "Nginx HTTPS may not be configured correctly"
fi

# Final summary
echo
echo "=================================================="
echo -e "${GREEN}🎉 RESTORE COMPLETED! 🎉${NC}"
echo "=================================================="
echo "Restored from: ${BACKUP_PATH}"
echo "Restoration includes:"
echo "  ✅ Configuration files"
echo "  ✅ Nginx configuration & SSL certificates"
echo "  ✅ MongoDB database"
echo "  ✅ User uploads & file storage"
echo "  ✅ Docker volumes"
echo
echo "Next steps:"
echo "  1. Verify services are running: systemctl status nginx"
echo "  2. Check Stoatchat API: curl http://localhost:14702/health"
echo "  3. Test frontend: visit https://st.vish.gg"
echo "  4. Check logs: tail -f ${STOATCHAT_DIR}/api.log"
echo
echo "If you encounter issues:"
echo "  - Check the backup info: cat ${BACKUP_PATH}/backup-info.txt"
echo "  - Review system info: cat ${BACKUP_PATH}/system/"
echo "  - Restart services: ${STOATCHAT_DIR}/manage-services.sh restart"
echo
echo "Restore completed at: $(date)"
echo "=================================================="
