#!/bin/bash

# Define color codes for echo
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m' # No color

# Define log files
ERROR_LOG="error.log"
INSTALL_LOG="install.log"

# Function to log and echo status messages
log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') [ERROR] $1" >> "$ERROR_LOG"
}

log_status() {
    echo -e "${YELLOW}[STATUS]${NC} $1"
}

# Start script
log_status "Starting Node.js v22 installation on Ubuntu 22.04..."

# Update package list
log_status "Updating package list..."
if ! sudo apt update; then
    log_error "Failed to update package list."
    exit 1
fi

# Install prerequisites
log_status "Installing prerequisites..."
if ! sudo apt install -y curl; then
    log_error "Failed to install prerequisites."
    exit 1
fi

# Download and setup Node.js v22
log_status "Setting up Node.js v22 repository..."
if ! curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -; then
    log_error "Failed to set up Node.js repository."
    exit 1
fi

log_status "Installing Node.js v22..."
if ! sudo apt install -y nodejs; then
    log_error "Failed to install Node.js."
    exit 1
fi

# Check installation
log_status "Verifying Node.js installation..."
if node -v | grep -q "v22"; then
    log_success "Node.js v22 installed successfully."
    echo "$(date '+%Y-%m-%d %H:%M:%S') nodejs ok" >> "$INSTALL_LOG"
else
    log_error "Node.js v22 installation verification failed."
    exit 1
fi

log_success "Node.js v22 installation completed. Logs saved to $INSTALL_LOG and $ERROR_LOG."
