$ErrorActionPreference = 'Stop' # Stop on all errors

# Define the package arguments
$packageArgs = @{
    packageName   = $env:ChocolateyPackageName
    unzipLocation = Join-Path $env:LOCALAPPDATA 'com.toki-labs.oto'
    url           = 'http://toki-labs.com/cdn/oto/windows/oto_x64_v0.0.287.zip'
    url64bit      = 'http://toki-labs.com/cdn/oto/windows/oto_x64_v0.0.287.zip'
    checksum      = '' # Optional: Provide checksum if available
    checksumType  = 'sha256' # Adjust if checksum is provided
    validExitCodes= @(0) # Only exit code 0 is considered valid
}

# Ensure the destination folder exists
if (-Not (Test-Path -Path $packageArgs.unzipLocation)) {
    New-Item -ItemType Directory -Path $packageArgs.unzipLocation -Force | Out-Null
}

# Use Chocolatey helper function to download and unzip the file
Install-ChocolateyZipPackage `
    $packageArgs.packageName `
    $packageArgs.url `
    $packageArgs.unzipLocation `
    -url64 $packageArgs.url64bit `
    -checksum $packageArgs.checksum `
    -checksumType $packageArgs.checksumType

# Add the oto.exe to the PATH environment variable
$otoPath = $packageArgs.unzipLocation
if (Test-Path -Path $otoPath) {
    Write-Host "Adding $otoPath to the PATH environment variable..."
    $currentPath = [System.Environment]::GetEnvironmentVariable('Path', [System.EnvironmentVariableTarget]::User)
    if (-Not ($currentPath -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ieq $otoPath })) {
        [System.Environment]::SetEnvironmentVariable('Path', "$currentPath;$otoPath", [System.EnvironmentVariableTarget]::User)
        Write-Host "oto.exe has been added to the PATH."
    } else {
        Write-Host "oto.exe is already in the PATH."
    }
} else {
    Write-Host "Error: oto.exe not found in $packageArgs.unzipLocation."
}

# Step 3: Execute startup script if it exists
$startupScriptPath = Join-Path $env:LOCALAPPDATA "com.toki-labs.oto/startup/com.toki-labs.oto.ps1"
# $otoExePath = Join-Path $env:LOCALAPPDATA "com.toki-labs.oto/oto.exe"
if (Test-Path $startupScriptPath) {
    Write-Host "Found startup script at $startupScriptPath. Attempting to run as non-admin user..."

    # 현재 시간 기준으로 1분 뒤의 시간 계산
    $currentTime = Get-Date
    $futureTime = $currentTime.AddMinutes(1).ToString("HH:mm")

    # schtasks 명령어로 작업 생성 및 실행
    $taskName = "RunStartupScript_" + [guid]::NewGuid().ToString()
    schtasks /Create /F /RU "$env:USERNAME" /SC ONCE /ST $futureTime /TN $taskName /TR "powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"$startupScriptPath`""
    schtasks /Run /TN $taskName
    schtasks /Delete /F /TN $taskName
} else {
    Write-Host "Startup script not found at $startupScriptPath. Skipping execution."
}

Write-Host "Installation completed successfully!"
