Install-BookmarkBackupTool.ps1

# =====================================================================================
# BookmarkBackupTool Module Installation Script - Fixed
# =====================================================================================

[CmdletBinding()]
param(
    [Parameter(Mandatory = $false)]
    [ValidateSet('CurrentUser', 'AllUsers')]
    [string]$Scope = 'CurrentUser',
    
    [Parameter(Mandatory = $false)]
    [switch]$Force
)

$ErrorActionPreference = 'Stop'

Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "BookmarkBackupTool Module Installer" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan

# Safely get PowerShell edition
$psEditionValue = $PSVersionTable.PSEdition
if ([string]::IsNullOrEmpty($psEditionValue)) {
    $psEditionValue = 'Desktop'  # Default for Windows PowerShell 5.1
}
$psVersion = $PSVersionTable.PSVersion

Write-Host "PowerShell Edition: $psEditionValue" -ForegroundColor Yellow
Write-Host "PowerShell Version: $psVersion`n" -ForegroundColor Yellow

# Validate PowerShell version
if ($psVersion.Major -lt 5 -or ($psVersion.Major -eq 5 -and $psVersion.Minor -lt 1)) {
    Write-Error "PowerShell 5.1 or higher is required. Current version: $psVersion"
    exit 1
}

# Determine module installation path
if ($Scope -eq 'CurrentUser') {
    if ($psEditionValue -eq 'Core') {
        $modulePath = Join-Path $env:USERPROFILE "Documents\PowerShell\Modules"
    } else {
        $modulePath = Join-Path $env:USERPROFILE "Documents\WindowsPowerShell\Modules"
    }
    Write-Host "Installation Scope: Current User" -ForegroundColor Green
} else {
    if ($psEditionValue -eq 'Core') {
        $modulePath = Join-Path $env:ProgramFiles "PowerShell\Modules"
    } else {
        $modulePath = Join-Path $env:ProgramFiles "WindowsPowerShell\Modules"
    }
    Write-Host "Installation Scope: All Users (requires Administrator)" -ForegroundColor Yellow
}

$targetPath = Join-Path $modulePath "BookmarkBackupTool"
Write-Host "Target Path: $targetPath`n" -ForegroundColor Cyan

# Check for required files
$requiredFiles = @(
    'BookmarkBackupTool.psm1',
    'BookmarkBackupTool.psd1'
)

$currentPath = $PSScriptRoot
if ([string]::IsNullOrEmpty($currentPath)) {
    $currentPath = Get-Location
}

Write-Host "Checking for required files in: $currentPath" -ForegroundColor Yellow
$missingFiles = @()

foreach ($file in $requiredFiles) {
    $filePath = Join-Path $currentPath $file
    if (Test-Path $filePath) {
        Write-Host " [OK] Found: $file" -ForegroundColor Green
    } else {
        Write-Host " [MISSING] $file" -ForegroundColor Red
        $missingFiles += $file
    }
}

if ($missingFiles.Count -gt 0) {
    Write-Error "Missing required files: $($missingFiles -join ', ')"
    Write-Host "`nPlease ensure all module files are in the current directory." -ForegroundColor Yellow
    exit 1
}

# Check if module already exists
if (Test-Path $targetPath) {
    if ($Force) {
        Write-Host "`nExisting module found. Removing due to -Force parameter..." -ForegroundColor Yellow
        Remove-Item -Path $targetPath -Recurse -Force
    } else {
        Write-Host "`nModule already exists at: $targetPath" -ForegroundColor Yellow
        $response = Read-Host "Overwrite existing installation? (Y/N)"
        if ($response -ne 'Y' -and $response -ne 'y') {
            Write-Host "Installation cancelled." -ForegroundColor Yellow
            exit 0
        }
        Remove-Item -Path $targetPath -Recurse -Force
    }
}

# Create module directory
Write-Host "`nCreating module directory..." -ForegroundColor Yellow
try {
    New-Item -ItemType Directory -Path $targetPath -Force | Out-Null
    Write-Host " [OK] Directory created" -ForegroundColor Green
} catch {
    Write-Error "Failed to create directory: $_"
    exit 1
}

# Copy module files
Write-Host "`nCopying module files..." -ForegroundColor Yellow
try {
    foreach ($file in $requiredFiles) {
        $sourcePath = Join-Path $currentPath $file
        $destPath = Join-Path $targetPath $file
        Copy-Item -Path $sourcePath -Destination $destPath -Force
        Write-Host " [OK] Copied: $file" -ForegroundColor Green
    }
    
    # Copy optional files if they exist
    $optionalFiles = @('README.md', 'config.template.json', 'LICENSE', 'en-US')
    foreach ($file in $optionalFiles) {
        $sourcePath = Join-Path $currentPath $file
        if (Test-Path $sourcePath) {
            $destPath = Join-Path $targetPath $file
            if ((Get-Item $sourcePath) -is [System.IO.DirectoryInfo]) {
                Copy-Item -Path $sourcePath -Destination $destPath -Recurse -Force
            } else {
                Copy-Item -Path $sourcePath -Destination $destPath -Force
            }
            Write-Host " [OK] Copied: $file (optional)" -ForegroundColor Green
        }
    }
} catch {
    Write-Error "Failed to copy files: $_"
    exit 1
}

# Verify installation
Write-Host "`nVerifying installation..." -ForegroundColor Yellow
try {
    Import-Module BookmarkBackupTool -Force -ErrorAction Stop
    $module = Get-Module BookmarkBackupTool
    
    if ($module) {
        Write-Host " [OK] Module loaded successfully" -ForegroundColor Green
        Write-Host " Version: $($module.Version)" -ForegroundColor Cyan
        Write-Host " Path: $($module.Path)" -ForegroundColor Cyan
        
        # Display exported functions
        $functions = $module.ExportedFunctions.Keys | Sort-Object
        Write-Host "`n Exported Functions ($($functions.Count)):" -ForegroundColor Cyan
        foreach ($func in $functions) {
            Write-Host " - $func" -ForegroundColor Gray
        }
        
        # Display aliases
        $aliases = $module.ExportedAliases.Keys | Sort-Object
        if ($aliases.Count -gt 0) {
            Write-Host "`n Exported Aliases ($($aliases.Count)):" -ForegroundColor Cyan
            foreach ($alias in $aliases) {
                Write-Host " - $alias" -ForegroundColor Gray
            }
        }
    } else {
        Write-Warning "Module loaded but could not retrieve module information"
    }
} catch {
    Write-Error "Failed to load module: $_"
    Write-Host "`nModule files were copied but could not be loaded." -ForegroundColor Yellow
    Write-Host "Try running: Import-Module BookmarkBackupTool" -ForegroundColor Yellow
    exit 1
}

# Success message
Write-Host "`n========================================" -ForegroundColor Green
Write-Host "Installation Completed Successfully!" -ForegroundColor Green
Write-Host "========================================`n" -ForegroundColor Green

Write-Host "Module installed to: $targetPath" -ForegroundColor Cyan
Write-Host "`nQuick Start Commands:" -ForegroundColor Yellow
Write-Host " Show-BookmarkGUI # Launch GUI" -ForegroundColor White
Write-Host " Export-Bookmarks -Path 'D:\Backup' -Chrome # Export bookmarks" -ForegroundColor White
Write-Host " Import-Bookmarks -Path 'D:\Backup' -Chrome # Import bookmarks" -ForegroundColor White
Write-Host " Get-Help Export-Bookmarks -Full # View detailed help" -ForegroundColor White

Write-Host "`nFor more information, run:" -ForegroundColor Yellow
Write-Host " Get-Command -Module BookmarkBackupTool`n" -ForegroundColor White

# Ask about profile setup
Write-Host "Would you like to add the module to your PowerShell profile" -ForegroundColor Yellow
Write-Host "for automatic loading in future sessions? (Y/N): " -ForegroundColor Yellow -NoNewline
$profileResponse = Read-Host

if ($profileResponse -eq 'Y' -or $profileResponse -eq 'y') {
    $profilePath = $PROFILE
    
    # Create profile if it doesn't exist
    if (!(Test-Path $profilePath)) {
        Write-Host "Creating PowerShell profile..." -ForegroundColor Yellow
        $profileDir = Split-Path $profilePath -Parent
        if (!(Test-Path $profileDir)) {
            New-Item -ItemType Directory -Path $profileDir -Force | Out-Null
        }
        New-Item -ItemType File -Path $profilePath -Force | Out-Null
    }
    
    # Check if already in profile
    $profileContent = Get-Content $profilePath -Raw -ErrorAction SilentlyContinue
    if ($profileContent -notmatch 'BookmarkBackupTool') {
        Add-Content -Path $profilePath -Value "`n# BookmarkBackupTool Module"
        Add-Content -Path $profilePath -Value "Import-Module BookmarkBackupTool"
        Write-Host "[OK] Added to PowerShell profile: $profilePath" -ForegroundColor Green
        Write-Host "The module will load automatically in new PowerShell sessions." -ForegroundColor Cyan
    } else {
        Write-Host "[INFO] Module already configured in profile" -ForegroundColor Yellow
    }
}

Write-Host "`nInstallation complete! Enjoy using BookmarkBackupTool!`n" -ForegroundColor Green