#!/bin/bash

set -e # Exit on any error

echo "SWAI Local Installation Script"
echo "=============================="

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

# Get the current directory (where the script is located)
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo -e "${YELLOW}Step 1: Installing npm dependencies${NC}"
cd "$SOURCE_DIR"

# Run npm install
echo "Running npm install..."
npm install

echo -e "${GREEN}✓ Dependencies installed successfully${NC}"

echo -e "${YELLOW}Step 2: Installing system-wide${NC}"

# Check if running as root for system installation
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}System installation requires root privileges.${NC}"
    echo "You can either:"
    echo "1. Run this script with sudo"
    echo "2. Run the following commands manually as root:"
    echo ""
    echo "   sudo mkdir -p /usr/share/swai"
    echo "   sudo cp -a $SOURCE_DIR/* /usr/share/swai/"
    echo "   sudo install -m 755 $SOURCE_DIR/swai.sh /usr/bin/swai"
    echo "   sudo chmod +x /usr/bin/swai"
    echo ""
    echo -e "${YELLOW}Attempting to run installation commands with sudo...${NC}"

    sudo bootc usr-overlay || true

    # Try to run with sudo
    echo "Creating /usr/share/swai directory..."
    sudo mkdir -p /usr/share/swai

    echo "Copying application files..."
    sudo cp -a "$SOURCE_DIR"/* /usr/share/swai/

    echo "Installing swai command..."
    sudo install -m 755 "$SOURCE_DIR/swai.sh" /usr/bin/swai

    echo "Setting permissions..."
    sudo chmod +x /usr/bin/swai
else
    bootc usr-overlay || true

    # Running as root
    echo "Creating /usr/share/swai directory..."
    mkdir -p /usr/share/swai

    echo "Copying application files..."
    cp -a "$SOURCE_DIR"/* /usr/share/swai/

    echo "Installing swai command..."
    install -m 755 "$SOURCE_DIR/swai.sh" /usr/bin/swai

    echo "Setting permissions..."
    chmod +x /usr/bin/swai
fi

rm -rf ~/swai

echo -e "${GREEN}✓ System installation completed successfully${NC}"

echo ""
echo -e "${GREEN}Installation Summary:${NC}"
echo "• Source copied to: $SOURCE_DIR"
echo "• Application installed to: /usr/share/swai"
echo "• Command available as: /usr/bin/swai"
echo ""
echo -e "${YELLOW}Usage:${NC}"
echo "  swai /path/to/app.swai"
echo ""
echo -e "${YELLOW}Test installation:${NC}"
echo "  swai $SOURCE_DIR/testapps/html5test.swai"
echo ""
echo -e "${GREEN}Installation completed successfully!${NC}"
