# Sets up GitHub token for Humand private packages.
# Usage: setup-github-token.ps1 -Token <token>
param(
  [Parameter(Mandatory=$true)]
  [string]$Token
)

$HumandDir = Join-Path $HOME ".humand"
$TokenFile = Join-Path $HumandDir "github-token"
$NpmrcFile = Join-Path $HOME ".npmrc"

# Create directory
New-Item -ItemType Directory -Force -Path $HumandDir | Out-Null

# Save token
Set-Content -Path $TokenFile -Value $Token -NoNewline
# Restrict permissions (Windows equivalent of chmod 600)
$acl = Get-Acl $TokenFile
$acl.SetAccessRuleProtection($true, $false)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
  [System.Security.Principal.WindowsIdentity]::GetCurrent().Name,
  "FullControl", "Allow"
)
$acl.AddAccessRule($rule)
Set-Acl -Path $TokenFile -AclObject $acl

# Update .npmrc — remove existing Humand entries first
if (Test-Path $NpmrcFile) {
  $lines = Get-Content $NpmrcFile | Where-Object {
    $_ -notmatch "@humanddev:registry" -and $_ -notmatch "npm\.pkg\.github\.com"
  }
  Set-Content -Path $NpmrcFile -Value $lines
}

# Append new entries
Add-Content -Path $NpmrcFile -Value "@humanddev:registry=https://npm.pkg.github.com"
Add-Content -Path $NpmrcFile -Value "//npm.pkg.github.com/:_authToken=$Token"

Write-Host "Token guardado en $TokenFile"
Write-Host ".npmrc actualizado en $NpmrcFile"
