# Install-AlephComplete.ps1
# Complete script to install WSL, Ubuntu with default credentials, and Aleph.im
# This script must be run with administrative privileges

# Check if running as administrator
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "Please run this script as Administrator!" -ForegroundColor Red
    break
}

# Function to display colored text
function Write-ColoredText {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Text,
        
        [Parameter(Mandatory=$true)]
        [ValidateSet("Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")]
        [string]$ForegroundColor
    )
    
    Write-Host $Text -ForegroundColor $ForegroundColor
}

# Display introduction
Write-ColoredText "===== Aleph.im Complete Installation Script =====" "Cyan"
Write-ColoredText "This script will:" "White"
Write-ColoredText "  1. Uninstall any existing WSL distributions" "White"
Write-ColoredText "  2. Install WSL and Ubuntu" "White"
Write-ColoredText "  3. Set up Ubuntu with default credentials (alephGui/alephGui!)" "White"
Write-ColoredText "  4. Install Aleph.im and its dependencies" "White"
Write-ColoredText "==============================================" "Cyan"
## Write-ColoredText "Press Enter to continue or Ctrl+C to cancel..." "Yellow"
## Read-Host

#########################
# PART 1: WSL and Ubuntu Installation
#########################

Write-ColoredText "PART 1: Installing WSL and Ubuntu..." "Magenta"

# Step 1: 使用基于编码处理的方法解析WSL发行版
Write-ColoredText "Step 1: Uninstalling all existing WSL distributions..." "Cyan"

# 创建临时文件路径
$tempDir = [System.IO.Path]::GetTempPath()
$wslOutputFile = Join-Path $tempDir "wsl_list_utf16.txt"

# 将WSL列表导出到临时文件
Write-ColoredText "Exporting WSL distribution list to temp file..." "Yellow"
cmd /c "wsl -l -v > $wslOutputFile"

# 显示当前WSL发行版列表
$wslOutput = Get-Content -Encoding Unicode $wslOutputFile -Raw
Write-ColoredText "Current WSL distributions:" "Yellow"
Write-ColoredText $wslOutput "White"

# 使用PowerShell解析Ubuntu发行版
Write-ColoredText "Parsing Ubuntu distributions..." "Yellow"
$foundDistros = @()

# 读取文件并解析（注意编码为Unicode）
$lines = Get-Content -Encoding Unicode $wslOutputFile | Where-Object { $_ -match '\S' }
foreach ($line in $lines) {
    $line = $line.Trim()
    if ($line -match "Ubuntu") {
        # 去除开头的*号并分割行
        $lineParts = $line -split '\s+'
        $distroName = $null
        
        # 检查是否以*开头
        if ($lineParts[0] -eq "*") {
            if ($lineParts.Length -ge 2) {
                $distroName = $lineParts[1]
            }
        } else {
            $distroName = $lineParts[0]
        }
        
        if ($distroName) {
            Write-ColoredText "Found Ubuntu distribution: $distroName" "Green"
            $foundDistros += $distroName
        }
    }
}

# 卸载找到的发行版
if ($foundDistros.Count -gt 0) {
    foreach ($distro in $foundDistros) {
        Write-ColoredText "Unregistering $distro..." "Yellow"
        wsl --unregister $distro
        Start-Sleep -Seconds 2
    }
} else {
    Write-ColoredText "No Ubuntu distributions found to unregister." "Yellow"
}

# 清理临时文件
Remove-Item -Path $wslOutputFile -Force -ErrorAction SilentlyContinue

# 备份方法：直接尝试卸载常见发行版
Write-ColoredText "Performing direct unregistration of common distributions..." "Yellow"
$commonDistros = @("Ubuntu", "Ubuntu-20.04", "Ubuntu-22.04", "Ubuntu-24.04")
foreach ($distro in $commonDistros) {
    try {
        Write-ColoredText "Attempting to unregister $distro (if it exists)..." "White"
        wsl --unregister $distro 2>$null
    } catch {
        # 忽略错误，因为这只是额外的安全措施
    }
}

# Step 2: Disable and re-enable WSL feature
Write-ColoredText "Step 2: Disabling WSL feature..." "Cyan"
dism.exe /online /disable-feature /featurename:Microsoft-Windows-Subsystem-Linux /norestart

Write-ColoredText "Step 3: Re-enabling WSL feature..." "Cyan"
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

Write-ColoredText "Step 4: Enabling Virtual Machine Platform..." "Cyan"
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

Write-ColoredText "Step 5: Setting WSL default version to 2..." "Cyan"
wsl --set-default-version 2

# Step 6: Install Ubuntu
Write-ColoredText "Step 6: Installing Ubuntu via WSL..." "Cyan"

# Directly use WSL command to install Ubuntu
Write-ColoredText "Using WSL command to install Ubuntu..." "Yellow"
wsl --install -d Ubuntu

# Step 7: 使用编码处理方法检查Ubuntu安装
Write-ColoredText "Step 7: Waiting for Ubuntu installation to complete..." "Cyan"
Start-Sleep -Seconds 30

# Ubuntu安装检测函数
function Test-UbuntuInstalled {
    # 创建临时文件路径
    $tempDir = [System.IO.Path]::GetTempPath()
    $wslCheckFile = Join-Path $tempDir "wsl_check_utf16.txt"
    
    # 导出WSL列表到临时文件
    cmd /c "wsl --list > $wslCheckFile"
    
    # 使用正确的编码读取文件
    $found = $false
    if (Test-Path $wslCheckFile) {
        $content = Get-Content -Encoding Unicode $wslCheckFile
        
        foreach ($line in $content) {
            $line = $line.Trim()
            if ($line -match "Ubuntu") {
                $found = $true
                break
            }
        }
        
        # 清理临时文件
        Remove-Item -Path $wslCheckFile -Force -ErrorAction SilentlyContinue
    }
    
    return $found
}

# 检查Ubuntu是否安装
$ubuntuInstalled = $false
$maxAttempts = 10
$attempt = 0

while (-not $ubuntuInstalled -and $attempt -lt $maxAttempts) {
    $attempt++
    Write-ColoredText "Checking if Ubuntu is installed (attempt $attempt of $maxAttempts)..." "Yellow"
    
    if (Test-UbuntuInstalled) {
        $ubuntuInstalled = $true
        Write-ColoredText "Ubuntu is installed successfully!" "Green"
    } else {
        Write-ColoredText "Ubuntu not detected yet. Waiting 30 seconds before checking again..." "Yellow"
        Start-Sleep -Seconds 30
    }
}

if (-not $ubuntuInstalled) {
    Write-ColoredText "Ubuntu installation could not be confirmed after $maxAttempts attempts." "Red"
    Write-ColoredText "Please try the following manual steps:" "Yellow"
    Write-ColoredText "1. Open Microsoft Store and search for Ubuntu" "Yellow"
    Write-ColoredText "2. Install Ubuntu 24.04 LTS or any available version" "Yellow"
    Write-ColoredText "3. After installation completes, run this script again" "Yellow"
    exit 1
}

# Step 8: 逐行执行命令，修复行尾和参数传递问题
Write-ColoredText "Step 8: Setting up Ubuntu with default user..." "Cyan"

# 不使用文件传输，而是直接执行单个命令
Write-ColoredText "Running commands to set up user..." "Yellow"

# 执行命令以创建用户
wsl -d Ubuntu -- bash -c "sudo apt update"
wsl -d Ubuntu -- bash -c "sudo apt -y install sudo"
wsl -d Ubuntu -- bash -c "sudo useradd -m -s /bin/bash alephGui"
wsl -d Ubuntu -- bash -c "echo 'alephGui:alephGui!' | sudo chpasswd"
wsl -d Ubuntu -- bash -c "sudo usermod -aG sudo alephGui"
wsl -d Ubuntu -- bash -c "echo 'alephGui ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/alephGui"
wsl -d Ubuntu -- bash -c "echo -e '[user]\ndefault=alephGui' | sudo tee /etc/wsl.conf"
wsl -d Ubuntu -- bash -c "sudo chown -R alephGui:alephGui /home/alephGui 2>/dev/null || true"
# Start-Process -FilePath ".\assets\setup_aleph_user.bat" -Wait # 或者使用PowerShell Start-Process调用 bat 文件安装

# 重启WSL应用更改
Write-ColoredText "Restarting WSL to apply user configuration..." "Yellow"
wsl --shutdown
Start-Sleep -Seconds 10

# 验证用户是否创建成功
$userCheck = wsl -d Ubuntu -- id -u alephGui 2>&1
if ($LASTEXITCODE -ne 0 -or $userCheck -match "no such user") {
    Write-ColoredText "WARNING: User alephGui was not created successfully. Trying once more..." "Red"
    
    # 再次尝试直接创建用户
    Write-ColoredText "Attempting to create user again..." "Yellow"
    wsl -d Ubuntu -- sudo useradd -m -s /bin/bash alephGui
    wsl -d Ubuntu -- sudo bash -c "echo 'alephGui:alephGui!' | sudo chpasswd"
    wsl -d Ubuntu -- sudo usermod -aG sudo alephGui
    wsl -d Ubuntu -- sudo bash -c "echo 'alephGui ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/alephGui"
    wsl -d Ubuntu -- sudo bash -c "echo -e '[user]\ndefault=alephGui' | sudo tee /etc/wsl.conf"
    
    # 再次重启WSL
    wsl --shutdown
    Start-Sleep -Seconds 10
    
    # 再次验证用户
    $userCheck = wsl -d Ubuntu -- id -u alephGui 2>&1
    if ($LASTEXITCODE -ne 0 -or $userCheck -match "no such user") {
        Write-ColoredText "ERROR: Could not create alephGui user after multiple attempts." "Red"
        $userCreated = $false
    } else {
        Write-ColoredText "SUCCESS: User alephGui was created successfully on second attempt." "Green"
        $userCreated = $true
    }
} else {
    Write-ColoredText "SUCCESS: User alephGui was created successfully." "Green"
    $userCreated = $true
}

Write-ColoredText "Part 1 completed: WSL and Ubuntu installation with default credentials" "Green"










#########################
# PART 2: Aleph.im Installation - 安装 aleph.im
#########################

Write-ColoredText "PART 2: Installing Aleph.im..." "Magenta"

# 检查Ubuntu是否可访问
$ubuntuAccessible = $false
try {
    $ubuntuCheck = wsl -d Ubuntu -- echo "WSL Ubuntu check"
    if ($ubuntuCheck -match "check") {
        $ubuntuAccessible = $true
        Write-ColoredText "WSL Ubuntu is accessible. Proceeding with Aleph.im installation..." "Green"
    }
}
catch {
    Write-ColoredText "Error accessing Ubuntu. Trying to restart WSL..." "Yellow"
}

if (-not $ubuntuAccessible) {
    Write-ColoredText "Restarting WSL to ensure accessibility..." "Yellow"
    wsl --shutdown
    Start-Sleep -Seconds 10
    try {
        $ubuntuCheck = wsl -d Ubuntu -- echo "WSL Ubuntu check retry"
        if ($ubuntuCheck -match "check") {
            $ubuntuAccessible = $true
            Write-ColoredText "WSL Ubuntu is now accessible" "Green"
        }
    }
    catch {
        Write-ColoredText "Error: Cannot access Ubuntu. Please restart your computer and run Part 2 of this script." "Red"
        exit 1
    }
}

# 安装Aleph.im 
Write-ColoredText "Installing Aleph.im..." "Cyan"

# 根据用户创建状态选择执行命令的用户
if ($userCreated) {
    Write-ColoredText "Installing Aleph.im as user alephGui..." "Yellow"

    # 系统包更新
    wsl -d Ubuntu -u alephGui -- sudo apt update
    wsl -d Ubuntu -u alephGui -- sudo apt upgrade -y
    wsl -d Ubuntu -u alephGui -- sudo apt-get install -y python3-pip libsecp256k1-dev
    wsl -d Ubuntu -u alephGui -- sudo apt install -y pipx

    # 确保 pipx 在 PATH，并一步完成：install + inject click==8.1.7
    wsl -d Ubuntu -u alephGui -- bash -lc `
      "pipx ensurepath && \
       pipx install aleph-client && \
       pipx inject aleph-client click==8.1.7"

    if ($LASTEXITCODE -ne 0) {
        Write-ColoredText "Aleph-client 安装或注入 click 失败，尝试备用方案..." "Yellow"
        wsl -d Ubuntu -u alephGui -- bash -lc `
          "python3 -m pip install --user pipx && \
           pipx ensurepath && \
           pipx install aleph-client && \
           pipx inject aleph-client click==8.1.7"
    }

    # 创建测试文件
    wsl -d Ubuntu -u alephGui -- mkdir -p ~/aleph-test
    wsl -d Ubuntu -u alephGui -- bash -lc "echo 'This is a test file for Aleph.im' > ~/aleph-test/test.txt"

    # 验证 aleph 命令是否可用
    $alephPath = wsl -d Ubuntu -u alephGui -- bash -lc "which aleph 2>/dev/null || echo 'not found'"
} else {
    Write-ColoredText "Installing Aleph.im as default user..." "Yellow"
    
    wsl -d Ubuntu -- sudo apt update
    wsl -d Ubuntu -- sudo apt upgrade -y
    wsl -d Ubuntu -- sudo apt-get install -y python3-pip libsecp256k1-dev
    wsl -d Ubuntu -- sudo apt install -y pipx
    wsl -d Ubuntu -- pipx ensurepath
    wsl -d Ubuntu -- bash -c "export PATH=\"\$HOME/.local/bin:\$PATH\""
    wsl -d Ubuntu -- bash -c "echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.bashrc"
    
    # 尝试安装aleph-client
    wsl -d Ubuntu -- pipx install aleph-client
    if ($LASTEXITCODE -ne 0) {
        Write-ColoredText "First attempt to install aleph-client failed, trying alternative method..." "Yellow"
        wsl -d Ubuntu -- python3 -m pip install --user pipx
        wsl -d Ubuntu -- python3 -m pipx ensurepath
        wsl -d Ubuntu -- bash -c "export PATH=\"\$HOME/.local/bin:\$PATH\""
        wsl -d Ubuntu -- python3 -m pipx install aleph-client
    }
    
    # 创建测试文件
    wsl -d Ubuntu -- mkdir -p ~/aleph-test
    wsl -d Ubuntu -- bash -c "echo 'This is a test file for Aleph.im' > ~/aleph-test/test.txt"
    
    # 验证安装
    $alephPath = wsl -d Ubuntu -- bash -c "which aleph 2>/dev/null || echo 'not found'"
}

# 验证Aleph.im安装
Write-ColoredText "Verifying Aleph.im installation..." "Yellow"
if ($alephPath -and $alephPath -ne "not found") {
    Write-ColoredText "Aleph.im successfully installed at: $alephPath" "Green"
    $alephInstalled = $true
} else {
    Write-ColoredText "Aleph.im may not be installed correctly. It was not found in PATH." "Red"
    
    # 尝试在.local目录中查找
    if ($userCreated) {
        $localPath = wsl -d Ubuntu -u alephGui -- bash -c "find ~/.local -name aleph -type f 2>/dev/null || echo 'not found'"
    } else {
        $localPath = wsl -d Ubuntu -- bash -c "find ~/.local -name aleph -type f 2>/dev/null || echo 'not found'"
    }
    
    if ($localPath -and $localPath -ne "not found") {
        Write-ColoredText "Found Aleph.im at: $localPath" "Green"
        Write-ColoredText "Adding to PATH..." "Yellow"
        
        # 使用WSL内部命令提取目录路径，避免在PowerShell中处理
        if ($userCreated) {
            # 先获取目录路径
            $dirPath = wsl -d Ubuntu -u alephGui -- bash -c "dirname '$localPath'"
            # 然后添加到PATH
            wsl -d Ubuntu -u alephGui -- bash -c "echo 'export PATH=\"\${PATH}:$dirPath\"' >> ~/.bashrc"
        } else {
            # 先获取目录路径
            $dirPath = wsl -d Ubuntu -- bash -c "dirname '$localPath'"
            # 然后添加到PATH
            wsl -d Ubuntu -- bash -c "echo 'export PATH=\"\${PATH}:$dirPath\"' >> ~/.bashrc"
        }
        $alephInstalled = $true
    } else {
        Write-ColoredText "Could not locate Aleph.im executable." "Red"
        $alephInstalled = $false
    }
}

# 最终说明
Write-ColoredText "===== INSTALLATION COMPLETED! =====" "Green"
Write-ColoredText "To use Aleph.im in Ubuntu WSL:" "Cyan"
Write-ColoredText "1. Start Ubuntu: Type 'ubuntu' or 'wsl' in your command prompt" "Cyan"

if ($userCreated) {
    Write-ColoredText "2. You should be automatically logged in as alephGui" "Cyan"
    Write-ColoredText "   If prompted for credentials:" "Cyan"
    Write-ColoredText "   Username: alephGui" "Green"
    Write-ColoredText "   Password: alephGui!" "Green"
} else {
    Write-ColoredText "2. User alephGui could not be created. You will be logged in as default user." "Yellow"
}

if ($alephInstalled) {
    Write-ColoredText "3. Run Aleph.im commands using the 'aleph' command" "Cyan"
    Write-ColoredText "4. If 'aleph' command is not found, run: source ~/.bashrc" "Yellow"
} else {
    Write-ColoredText "3. Aleph.im installation may not have completed successfully." "Red"
    Write-ColoredText "   You may need to manually install it after logging into WSL:" "Yellow"
    Write-ColoredText "   sudo apt update && sudo apt install -y python3-pip libsecp256k1-dev pipx" "Yellow"
    Write-ColoredText "   pipx ensurepath" "Yellow"
    Write-ColoredText "   source ~/.bashrc" "Yellow"
    Write-ColoredText "   pipx install aleph-client" "Yellow"
}

Write-ColoredText "===============================" "Green"