# Install-AlephWSL-Preserve.ps1
# 保留现有Ubuntu并安装Aleph.im脚本（如果没有Ubuntu则安装）
# 此脚本必须以管理员权限运行

# 检查是否以管理员权限运行
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "请以管理员身份运行此脚本！" -ForegroundColor Red
    break
}

# 函数：显示彩色文本
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
}

# 显示介绍
Write-ColoredText "===== Aleph.im 保留安装脚本 =====" "Cyan"
Write-ColoredText "此脚本将：" "White"
Write-ColoredText "  1. 检查现有Ubuntu WSL发行版" "White"
Write-ColoredText "  2. 如果未安装，则安装Ubuntu" "White"
Write-ColoredText "  3. 设置Ubuntu用户凭据 (alephGui/alephGui!)" "White"
Write-ColoredText "  4. 安装Aleph.im及其依赖" "White"
Write-ColoredText "==============================================" "Cyan"
## Write-ColoredText "按Enter键继续，或按Ctrl+C取消..." "Yellow"
## Read-Host

#########################
# PART 1: 检查并安装WSL和Ubuntu
#########################

Write-ColoredText "PART 1: 检查WSL和Ubuntu安装状态..." "Magenta"

# Step 1: 检查WSL是否启用
Write-ColoredText "Step 1: 检查WSL功能是否启用..." "Cyan"
# $wslEnabled = $false
$wslCheck = Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

if ($wslCheck.State -eq "Enabled") {
    Write-ColoredText "WSL功能已启用。" "Green"
    # $wslEnabled = $true
} else {
    Write-ColoredText "WSL功能未启用，正在启用..." "Yellow"
    Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux -NoRestart
    Write-ColoredText "WSL功能已启用。" "Green"
    # $wslEnabled = $true
}

# Step 2: 检查Virtual Machine Platform是否启用
Write-ColoredText "Step 2: 检查Virtual Machine Platform功能是否启用..." "Cyan"
# $vmPlatformEnabled = $false
$vmPlatformCheck = Get-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform

if ($vmPlatformCheck.State -eq "Enabled") {
    Write-ColoredText "Virtual Machine Platform功能已启用。" "Green"
    # $vmPlatformEnabled = $true
} else {
    Write-ColoredText "Virtual Machine Platform功能未启用，正在启用..." "Yellow"
    Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform -NoRestart
    Write-ColoredText "Virtual Machine Platform功能已启用。" "Green"
    # $vmPlatformEnabled = $true
}

# Step 3: 设置WSL默认版本为2
Write-ColoredText "Step 3: 设置WSL默认版本为2..." "Cyan"
wsl --set-default-version 2
Write-ColoredText "WSL默认版本已设置为2。" "Green"

# Step 4: 检查是否已安装Ubuntu
Write-ColoredText "Step 4: 检查是否已安装Ubuntu..." "Cyan"

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

# 将WSL列表导出到临时文件
cmd /c "wsl -l -v > $wslOutputFile"

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

# 检查是否有Ubuntu发行版
$ubuntuFound = $false
$ubuntuDistro = ""

# 读取文件并解析
$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 "找到Ubuntu发行版: $distroName" "Green"
            $ubuntuFound = $true
            $ubuntuDistro = $distroName
            break
        }
    }
}

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

# Step 5: 如果未找到Ubuntu，则安装
if (-not $ubuntuFound) {
    Write-ColoredText "未找到Ubuntu发行版，正在安装..." "Yellow"
    
    # 使用WSL命令安装Ubuntu
    Write-ColoredText "使用WSL命令安装Ubuntu..." "Yellow"
    wsl --install -d Ubuntu
    
    # 等待安装完成
    Write-ColoredText "等待Ubuntu安装完成..." "Cyan"
    Start-Sleep -Seconds 30
    
    # 改进的检测函数
    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 "检查Ubuntu是否已安装 (尝试 $attempt / $maxAttempts)..." "Yellow"
        
        if (Test-UbuntuInstalled) {
            $ubuntuInstalled = $true
            Write-ColoredText "Ubuntu安装成功！" "Green"
            $ubuntuDistro = "Ubuntu"
        } else {
            Write-ColoredText "尚未检测到Ubuntu。等待30秒后再次检查..." "Yellow"
            Start-Sleep -Seconds 30
        }
    }
    
    if (-not $ubuntuInstalled) {
        Write-ColoredText "在$maxAttempts次尝试后仍无法确认Ubuntu安装。" "Red"
        Write-ColoredText "请尝试以下手动步骤:" "Yellow"
        Write-ColoredText "1. 打开Microsoft Store并搜索Ubuntu" "Yellow"
        Write-ColoredText "2. 安装Ubuntu 24.04 LTS或任何可用版本" "Yellow"
        Write-ColoredText "3. 安装完成后，再次运行此脚本" "Yellow"
        exit 1
    }
} else {
    Write-ColoredText "已找到Ubuntu发行版: $ubuntuDistro，跳过安装步骤。" "Green"
}

# 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

# 重启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 - 使用正确的命令参数
#########################

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参数和命令
    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
    wsl -d Ubuntu -u alephGui -- pipx ensurepath
    wsl -d Ubuntu -u alephGui -- bash -c "export PATH=\"\$HOME/.local/bin:\$PATH\""
    wsl -d Ubuntu -u alephGui -- bash -c "echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.bashrc"
    
    # 尝试安装aleph-client
    wsl -d Ubuntu -u alephGui -- pipx install aleph-client
    if ($LASTEXITCODE -ne 0) {
        Write-ColoredText "First attempt to install aleph-client failed, trying alternative method..." "Yellow"
        wsl -d Ubuntu -u alephGui -- python3 -m pip install --user pipx
        wsl -d Ubuntu -u alephGui -- python3 -m pipx ensurepath
        wsl -d Ubuntu -u alephGui -- bash -c "export PATH=\"\$HOME/.local/bin:\$PATH\""
        wsl -d Ubuntu -u alephGui -- python3 -m pipx install aleph-client
    }
    
    # 创建测试文件
    wsl -d Ubuntu -u alephGui -- mkdir -p ~/aleph-test
    wsl -d Ubuntu -u alephGui -- bash -c "echo 'This is a test file for Aleph.im' > ~/aleph-test/test.txt"
    
    # 验证安装
    $alephPath = wsl -d Ubuntu -u alephGui -- bash -c "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"