#!/bin/bash

set -e

INSTALL_DIR="/opt/voiceforge"
SERVICE_NAME="voiceforge"
SERVICE_USER="voiceforge"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "This script must be run as root (use sudo)"
        exit 1
    fi
}

check_installation() {
    if [[ ! -d "$INSTALL_DIR" ]]; then
        log_error "VoiceForge is not installed. Run install.sh first."
        exit 1
    fi
}

backup_current() {
    BACKUP_DIR="/opt/voiceforge_backup_$(date +%Y%m%d_%H%M%S)"
    log_info "Creating backup at $BACKUP_DIR..."
    cp -r "$INSTALL_DIR" "$BACKUP_DIR"
    log_info "Backup created successfully"
}

update_application() {
    log_info "Stopping service..."
    systemctl stop ${SERVICE_NAME} || true

    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    
    if [[ -f "$SCRIPT_DIR/../package.json" ]]; then
        log_info "Updating application files..."
        
        cp "$INSTALL_DIR/.env" /tmp/voiceforge_env_backup 2>/dev/null || true
        
        rm -rf "$INSTALL_DIR/client" "$INSTALL_DIR/server" "$INSTALL_DIR/shared" "$INSTALL_DIR/dist"
        
        cp -r "$SCRIPT_DIR/../client" "$INSTALL_DIR/" 2>/dev/null || true
        cp -r "$SCRIPT_DIR/../server" "$INSTALL_DIR/" 2>/dev/null || true
        cp -r "$SCRIPT_DIR/../shared" "$INSTALL_DIR/" 2>/dev/null || true
        cp "$SCRIPT_DIR/../package.json" "$INSTALL_DIR/" 2>/dev/null || true
        cp "$SCRIPT_DIR/../package-lock.json" "$INSTALL_DIR/" 2>/dev/null || true
        cp "$SCRIPT_DIR/../tsconfig.json" "$INSTALL_DIR/" 2>/dev/null || true
        cp "$SCRIPT_DIR/../vite.config.ts" "$INSTALL_DIR/" 2>/dev/null || true
        cp "$SCRIPT_DIR/../tailwind.config.ts" "$INSTALL_DIR/" 2>/dev/null || true
        cp "$SCRIPT_DIR/../postcss.config.js" "$INSTALL_DIR/" 2>/dev/null || true
        cp "$SCRIPT_DIR/../drizzle.config.ts" "$INSTALL_DIR/" 2>/dev/null || true
        
        cp /tmp/voiceforge_env_backup "$INSTALL_DIR/.env" 2>/dev/null || true
        rm -f /tmp/voiceforge_env_backup
    else
        log_error "Update files not found. Please run from the extracted package directory."
        exit 1
    fi

    log_info "Installing dependencies..."
    cd "$INSTALL_DIR"
    npm ci --production=false --silent 2>/dev/null || npm install --silent

    log_info "Building application..."
    npm run build

    log_info "Setting permissions..."
    chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_DIR"

    log_info "Starting service..."
    systemctl start ${SERVICE_NAME}

    sleep 3

    if systemctl is-active --quiet ${SERVICE_NAME}; then
        log_info "Update completed successfully!"
    else
        log_error "Service failed to start after update"
        log_warn "Restoring from backup..."
        systemctl stop ${SERVICE_NAME} || true
        rm -rf "$INSTALL_DIR"
        mv "$BACKUP_DIR" "$INSTALL_DIR"
        systemctl start ${SERVICE_NAME}
        log_error "Update failed. Restored from backup."
        exit 1
    fi
}

main() {
    echo -e "${BLUE}"
    echo "╔═══════════════════════════════════════════════════════════╗"
    echo "║          VoiceForge Update Script                         ║"
    echo "╚═══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
    
    check_root
    check_installation
    backup_current
    update_application
    
    echo ""
    echo -e "${GREEN}✓ VoiceForge has been updated successfully!${NC}"
    echo ""
}

main "$@"
