# Sii Language Toolchain Setup Script for Windows PowerShell
# This script adds the bin directory to the system PATH environment variable

#Requires -RunAsAdministrator

$ErrorActionPreference = "Stop"

# Get the directory where this script is located
$SII_HOME = Split-Path -Parent $MyInvocation.MyCommand.Path
$BIN_PATH = Join-Path $SII_HOME "bin"

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Sii Language Toolchain Setup" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Installation directory: $SII_HOME"
Write-Host "Bin directory: $BIN_PATH"
Write-Host ""

# Check if running as administrator
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Host "ERROR: This script must be run as Administrator!" -ForegroundColor Red
    Write-Host ""
    Write-Host "Please right-click on this file and select 'Run as administrator'" -ForegroundColor Yellow
    Write-Host ""
    Read-Host "Press Enter to exit"
    exit 1
}

# Get current system PATH
$currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine")

# Check if PATH already contains the bin directory
if ($currentPath -like "*$BIN_PATH*") {
    Write-Host "The bin directory is already in PATH." -ForegroundColor Green
    Write-Host ""
    Read-Host "Press Enter to exit"
    exit 0
}

# Add to system PATH
Write-Host "Adding bin directory to system PATH..." -ForegroundColor Yellow
try {
    $newPath = "$currentPath;$BIN_PATH"
    [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine")
    Write-Host ""
    Write-Host "Successfully added $BIN_PATH to system PATH!" -ForegroundColor Green
    Write-Host ""
    Write-Host "IMPORTANT: Please close and reopen your PowerShell or Command Prompt" -ForegroundColor Yellow
    Write-Host "            for the changes to take effect." -ForegroundColor Yellow
    Write-Host ""
} catch {
    Write-Host ""
    Write-Host "ERROR: Failed to add to system PATH." -ForegroundColor Red
    Write-Host "Please add $BIN_PATH to PATH manually." -ForegroundColor Yellow
    Write-Host ""
    Write-Host "Error details: $_" -ForegroundColor Red
    Write-Host ""
    Read-Host "Press Enter to exit"
    exit 1
}

Read-Host "Press Enter to exit"
