#!/bin/bash
clear
# ==============================================================================
# n8n Updater Script for Debian 13 (Non-Docker)
# ==============================================================================
# This script safely updates a global npm installation of n8n.
# It stops the service, creates a backup, updates via npm, and restarts.
#
# Usage: sudo ./update_n8n.sh
# ==============================================================================

# --- CONFIGURATION ---
# Service name (usually 'n8n'). Check with: systemctl list-units --type=service | grep n8n
SERVICE_NAME="n8n"
# The system user n8n runs as (used for backup). often 'root', 'n8n', or your username.
# If unsure, check the service file: cat /etc/systemd/system/n8n.service
N8N_USER="root" 

# --- COLORS & FORMATTING ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
BOLD='\033[1m'

# --- HELPER FUNCTIONS ---

function log_header() {
    echo -e "\n${BOLD}${CYAN}========================================${NC}"
    echo -e "${BOLD}${CYAN}   $1${NC}"
    echo -e "${BOLD}${CYAN}========================================${NC}\n"
}

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

function log_success() {
    echo -e "${GREEN}[OK]${NC} $1"
}

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

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

function check_status() {
    if [ $? -eq 0 ]; then
        log_success "$1"
    else
        log_error "$2"
        exit 1
    fi
}

# --- MAIN SCRIPT EXECUTION ---

log_header "Starting n8n Update Process"

# 1. Check Root Privileges
if [[ $EUID -ne 0 ]]; then
   log_error "This script must be run as root. Please use sudo."
   exit 1
fi
log_success "Running with root privileges."

# 2. Verify Service Exists
if systemctl list-units --full -all | grep -Fq "$SERVICE_NAME.service"; then
    log_success "Service '$SERVICE_NAME' found."
else
    log_error "Service '$SERVICE_NAME' not found! Please check the SERVICE_NAME variable in the script."
    exit 1
fi

# 3. Stop the Service
log_info "Stopping $SERVICE_NAME service..."
systemctl stop "$SERVICE_NAME"
check_status "Service stopped successfully." "Failed to stop service. Aborting."

# 4. Backup (Optional but recommended)
# We try to find the .n8n folder based on the user configured at the top
HOME_DIR=$(eval echo "~$N8N_USER")
N8N_DIR="$HOME_DIR/.n8n"
BACKUP_DIR="$HOME_DIR/n8n_backups"

if [ -d "$N8N_DIR" ]; then
    log_info "Creating backup of configuration and database..."
    mkdir -p "$BACKUP_DIR"
    TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
    BACKUP_FILE="$BACKUP_DIR/n8n_backup_$TIMESTAMP.tar.gz"
    
    tar -czf "$BACKUP_FILE" -C "$HOME_DIR" .n8n 2>/dev/null
    
    if [ $? -eq 0 ]; then
        log_success "Backup created at: $BACKUP_FILE"
    else
        log_warning "Backup failed. Proceeding with caution."
    fi
else
    log_warning "Could not locate .n8n directory at $N8N_DIR. Skipping backup."
fi

# 5. Perform the Update
log_info "Updating n8n via npm (this may take a moment)..."
# We use --unsafe-perm=true to ensure scripts run correctly as root if needed
npm install -g n8n@latest --unsafe-perm=true
check_status "n8n package updated successfully." "npm update failed. Check your network or npm permissions."

# 6. Verify Version
NEW_VERSION=$(n8n --version)
log_info "Installed version is now: $NEW_VERSION"

# 7. Restart Service
log_info "Restarting $SERVICE_NAME service..."
systemctl start "$SERVICE_NAME"
check_status "Service start command executed." "Failed to start service."

# 8. Final Health Check
log_info "Verifying service health..."
sleep 3 # Give it a moment to spin up
if systemctl is-active --quiet "$SERVICE_NAME"; then
    log_header "Update Complete!"
    echo -e "${GREEN}SUCCESS:${NC} n8n has been updated to version ${BOLD}$NEW_VERSION${NC} and is running."
    echo -e "You can check logs with: ${YELLOW}journalctl -u $SERVICE_NAME -f${NC}"
else
    log_error "Service is not active! Please check logs: journalctl -u $SERVICE_NAME -e"
    exit 1
fi
