#!/bin/bash

################################################################################
# N3uron Installation Script
################################################################################
#
# PURPOSE:
#   Installs and updates N3uron on Linux systems.
#
# USAGE:
#   curl -fsSL https://get.n3uron.com/install.sh | sudo bash
#   curl -fsSL https://get.n3uron.com/install.sh | sudo env FORCE=true bash
#
# ENVIRONMENT VARIABLES:
#   FORCE              - Set to 'true' to force upgrade (default: false)
#   N3URON_SETUP_X64   - Custom URL for x64 package
#   N3URON_SETUP_ARM64 - Custom URL for ARM64 package
#
################################################################################

set -e

# -----------------------------------------------------------------------------
# Logging helpers (ASCII-only icons, no ANSI colors)
# -----------------------------------------------------------------------------

log_message() {
    local level="$1"
    local message="$2"
    local phase="$3"
    local icon=""
    local output_stream="1"
    
    case "$level" in
        INFO)
            icon="[INFO]"
        ;;
        WARN)
            icon="[WARN]"
            output_stream="2"
        ;;
        ERROR)
            icon="[ERROR]"
            output_stream="2"
        ;;
    esac
    
    local phase_label=""
    if [[ -n "$phase" ]]; then
        phase_label="[$phase] "
    fi
    
    if [[ "$output_stream" -eq 1 ]]; then
        printf '%s %s%s\n' "$icon" "$phase_label" "$message"
    else
        printf '%s %s%s\n' "$icon" "$phase_label" "$message" >&2
    fi
}

# Display informational message
info() {
    log_message "INFO" "$1" "$2"
}

# Display warning message (to stderr)
warn() {
    log_message "WARN" "$1" "$2"
}

# Display error message and exit
fatal() {
    log_message "ERROR" "$1" "$2"
    exit 1
}

echo -e "
    _   _______                           ________    ______
   / | / /__  /__  ___________  ____     /  _/  _/___/_  __/
  /  |/ / /_ </ / / / ___/ __ \/ __ \    / / / // __ \/ /
 / /|  /___/ / /_/ / /  / /_/ / / / /  _/ /_/ // /_/ / /
/_/ |_//____/\__,_/_/   \____/_/ /_/  /___/___/\____/_/

AI-Ready Industrial DataOps at Scale

What's new in v1.22:
  > MCP Server
  > TimescaleDB-powered Historian
  > Ethernet/IP Client
  > Sparkplug Host Application
  > ...and more
"

################################################################################
# CONFIGURATION
################################################################################

LATEST_VERSION="v1.22.7"
FORCE=${FORCE:-false}

# Download URLs for each architecture
N3URON_SETUP_X64=${N3URON_SETUP_X64:-"https://binaries.n3uron.com/release/n3uron-setup-1.22.7-x86_64-linux-gnu-261022.1105.tar.gz"}
N3URON_SETUP_ARM64=${N3URON_SETUP_ARM64:-"https://binaries.n3uron.com/release/n3uron-setup-1.22.7-aarch64-linux-gnu-261022.1105.tar.gz"}

# Installation and temporary directories
N3URON_INSTALL_DIR="/opt/n3uron"
N3URON_BIN="${N3URON_INSTALL_DIR}/bin/n3uron"
N3URON_INITD="/etc/init.d/n3uron"
N3URON_SYSTEMD_UNIT="/etc/systemd/system/n3uron.service"
SETUP_TARBALL_DIR="/tmp"

################################################################################
# FUNCTIONS
################################################################################

# Get the appropriate setup URL based on detected architecture
get_setup_url() {
    case "$ARCH" in
        x64)
            echo "$N3URON_SETUP_X64"
        ;;
        arm64)
            echo "$N3URON_SETUP_ARM64"
        ;;
        *)
            echo ""
        ;;
    esac
}

# Download N3uron setup package
download_package() {
    local url
    url="$(get_setup_url)"
    if [[ -z "$url" ]]; then
        fatal "Missing setup URL for ARCH=$ARCH. Set N3URON_SETUP_X64/N3URON_SETUP_ARM64"
    fi
    
    info "Downloading the installation package for $ARCH..."
    SETUP_TARBALL="${SETUP_TARBALL_DIR}/n3uron-setup-linux-${ARCH}.tar.gz"
    rm -f "$SETUP_TARBALL"
    curl -fL --progress-bar "$url" -o "$SETUP_TARBALL"
}

# Perform fresh installation of N3uron
install() {
    download_package
    
    # Extract setup package
    info "Installing into ${N3URON_INSTALL_DIR}"
    tar -xzf "$SETUP_TARBALL" -C /opt/
    
    # Make N3uron binary executable and run setup
    chmod +x "$N3URON_BIN"
    if ! "$N3URON_BIN" install > /dev/null 2>&1; then
        fatal "Installation failed."
    fi
    ensure_oom_policy
    
    # Clean up temporary files
    rm -f "$SETUP_TARBALL"
    
    # Start N3uron service
    info "Starting service..."
    start_service
}

# Make sure the init.d script is executable before calling "service".
# The N3uron installer creates it without the execute bit, and "service"
# reports a non-executable script as an unrecognized service.
ensure_initd_executable() {
    if [[ -f "$N3URON_INITD" && ! -x "$N3URON_INITD" ]]; then
        info "Restoring execute permission on ${N3URON_INITD}"
        chmod +x "$N3URON_INITD"
    fi
}

# Start N3uron service (handles both systemd and init.d)
start_service() {
    if [[ "$HAS_SYSTEMD" = true ]]; then
        systemctl start n3uron || fatal "Failed to start the N3uron service. Check: systemctl status n3uron"
    else
        ensure_initd_executable
        service n3uron start || fatal "Failed to start the N3uron service. Check: ${N3URON_INITD} status"
    fi
}

# Stop N3uron service (handles both systemd and init.d)
stop_service() {
    if [[ "$HAS_SYSTEMD" = true ]]; then
        systemctl stop n3uron || fatal "Failed to stop the N3uron service. Check: systemctl status n3uron"
    else
        ensure_initd_executable
        service n3uron stop || fatal "Failed to stop the N3uron service. Check: ${N3URON_INITD} status"
    fi
}

# Add OOMPolicy=continue to the systemd unit if it is missing.
# "n3uron install" writes it since v1.22.7, but upgrades only replace the
# binaries, so units written by older releases keep the systemd default
# (OOMPolicy=stop): an OOM kill in a single module restarts the whole
# service. Like fresh installs, systemd < 243 ignores the key with a warning.
# OOMPolicy is evaluated when the OOM kill happens, so daemon-reload is
# enough for a running service to pick it up.
ensure_oom_policy() {
    if [[ "$HAS_SYSTEMD" != true || ! -f "$N3URON_SYSTEMD_UNIT" ]]; then
        return 0
    fi
    
    # Keep any OOMPolicy already set, by the installer or by the user
    if grep -q '^[[:space:]]*OOMPolicy=' "$N3URON_SYSTEMD_UNIT"; then
        return 0
    fi
    
    info "Setting OOMPolicy=continue in ${N3URON_SYSTEMD_UNIT}"
    if sed -i '/^[[:space:]]*\[Service\]/a OOMPolicy=continue' "$N3URON_SYSTEMD_UNIT" &&
       grep -q '^OOMPolicy=continue$' "$N3URON_SYSTEMD_UNIT"; then
        systemctl daemon-reload || warn "Failed to reload systemd. Run: systemctl daemon-reload"
    else
        warn "Failed to set OOMPolicy in ${N3URON_SYSTEMD_UNIT}"
    fi
}

# Create timestamped backup of current N3uron configuration
# Stores backup in /opt/n3uron/data/bootstrap/backup/ directory
create_config_backup() {
    local backup_dir="${N3URON_INSTALL_DIR}/data/bootstrap/backup"
    local timestamp
    timestamp=$(date +"%Y%m%d_%H%M%S")
    local backup_file="${backup_dir}/config_backup_${timestamp}.zip"
    
    # Check if zip command is available
    if ! command -v zip &> /dev/null; then
        warn "zip command not found, skipping configuration backup"
        return 0
    fi
    
    # Create backups directory if it doesn't exist
    if [[ ! -d "$backup_dir" ]]; then
        mkdir -p "$backup_dir"
    fi
    
    info "Creating configuration backup..."
    
    # Check if config directory exists
    if [[ ! -d "${N3URON_INSTALL_DIR}/config" ]]; then
        warn "Configuration directory not found, skipping backup"
        return 0
    fi
    
    # Create backup using zip
    if (cd "${N3URON_INSTALL_DIR}/config" && zip -r -q "$backup_file" .) 2>/dev/null; then
        info "Configuration backup created: ${backup_file}"
        return 0
    else
        warn "Failed to create configuration backup"
        return 1
    fi
}

upgrade() {
    # Create configuration backup before proceeding
    create_config_backup
    
    download_package
    
    # Add OOMPolicy=continue to units written by older releases
    ensure_oom_policy
    
    # Stop the running N3uron service
    info "Stopping N3uron service..."
    stop_service
    
    # Extract new binaries files
    info "Installing N3uron to ${N3URON_INSTALL_DIR}"
    
    if [[ "$SKIP_OLD_FILES" == true ]]; then
        # For v1.20.x upgrades
        tar -xzf "$SETUP_TARBALL" -C /opt/ n3uron/bin
        tar -xzf "$SETUP_TARBALL" --skip-old-files -C /opt/ n3uron/config
    else
        # Update binaries only
        tar -xzf "$SETUP_TARBALL" -C /opt/ n3uron/bin
    fi
    
    # Clean up temporary files
    rm -f "$SETUP_TARBALL"
    
    # Start N3uron service
    info "Starting N3uron service..."
    start_service
}

detect_arch() {
    info "Detecting system architecture..."
    
    local machine_arch
    machine_arch=$(uname -m)
    
    case "$machine_arch" in
        x86_64)
            ARCH="x64"
        ;;
        aarch64)
            ARCH="arm64"
        ;;
        arm | armv*l)
            warn "N3uron v1.22 does not support the ARM32 architecture ($machine_arch)."
            info "You can download the latest ARM32-compatible release (N3uron v1.21) here: https://n3uron.com/downloads-software-v121/"
            exit 1
        ;;
        *)
            fatal "Unsupported architecture: $machine_arch"
        ;;
    esac
    info "Detected architecture: $ARCH"
}

print_summary() {
    printf '\n+------------------------------------------------------------------------------+\n'
    printf '| %-76s |\n' "N3uron ${LATEST_VERSION} successfully installed."
    printf '| %-76s |\n' ""
    printf '| %-76s |\n' "Release notes:  https://n3uron.com/releasenotes-v122/"
    printf '| %-76s |\n' "Academy:        https://n3uron.com/academy/"
    printf '| %-76s |\n' "AI Skills:      https://n3uron.com/skills"
    printf '| %-76s |\n' "Documentation:  https://docs.n3uron.com/"
    printf '| %-76s |\n' "Support:        https://n3uron.com/support/"
    printf '| %-76s |\n' ""
    printf '+------------------------------------------------------------------------------+\n\n'
}

# Check if running as root
if [ "$UID" -ne 0 ]; then
    fatal "This script requires root privileges. Please run with 'sudo'"
fi

# Check if OS is Linux
if [[ "$(uname)" != "Linux" ]]; then
    fatal "This script only runs on Linux"
fi

# Check if SystemD is available
HAS_SYSTEMD=false
if [ -x /bin/systemctl ] || type systemctl > /dev/null 2>&1; then
    HAS_SYSTEMD=true
fi

info "Checking if N3uron is already installed..."
# Check if N3uron is already installed
if ! test -f "$N3URON_BIN"; then
    info "N3uron is not installed, proceeding with the installation"
    detect_arch
    install
    print_summary
else
    # N3uron already installed - check if update is available
    VERSION=$("$N3URON_BIN" version 2>&1 | awk 'NR==1{print $2}')
    info "Detected installed N3uron version $VERSION"
    
    # Force upgrade if FORCE environment variable is set
    if [[ "$FORCE" == "true" ]]; then
        info "Upgrading N3uron to latest version $LATEST_VERSION"
        detect_arch
        upgrade
        print_summary
        exit 0
    fi
    
    # Check if installed version matches latest version
    if [[ "$VERSION" == "$LATEST_VERSION" ]]; then
        # Also covers units of installations upgraded without this script
        ensure_oom_policy
        info "N3uron is installed and up-to-date."
        exit 0
    else
        # Older version detected
        info "An older release of N3uron is installed: $VERSION"
        
        # Special handling for v1.20.x: warn user about additional steps
        if [[ "$VERSION" == v1.20* ]]; then
            warn "You are running N3uron v1.20.x, which requires special upgrade steps"
            info "See https://docs.n3uron.com/docs/platform-installation-and-upgrade-linux#upgrade-n3uron"
            
            # Prompt user to confirm upgrade
            read -rp "Do you want to proceed with the installation? (y/n): " answer </dev/tty
            
            # Convert answer to lowercase for case-insensitive comparison
            answer=${answer,,}
            if [[ "$answer" == "y" || "$answer" == "yes" ]]; then
                SKIP_OLD_FILES=true
                detect_arch
                upgrade
            else
                echo "Exiting..."
                exit 0
            fi
        else
            # Standard upgrade for newer versions
            detect_arch
            upgrade
            print_summary
        fi
    fi
fi

