#!/usr/bin/env bash
# Sets up GitHub token for Humand private packages.
# Usage: setup-github-token.sh <token>

set -euo pipefail

TOKEN="${1:-}"

if [[ -z "$TOKEN" ]]; then
  echo "Usage: setup-github-token.sh <github-token>" >&2
  exit 1
fi

HUMAND_DIR="$HOME/.humand"
TOKEN_FILE="$HUMAND_DIR/github-token"
NPMRC_FILE="$HOME/.npmrc"

mkdir -p "$HUMAND_DIR"
echo "$TOKEN" > "$TOKEN_FILE"
chmod 600 "$TOKEN_FILE"

# Preserve any existing .npmrc lines that are NOT about @humanddev or npm.pkg.github.com
if [[ -f "$NPMRC_FILE" ]]; then
  grep -v "@humanddev:registry\|npm\.pkg\.github\.com" "$NPMRC_FILE" > "$NPMRC_FILE.tmp" || true
  mv "$NPMRC_FILE.tmp" "$NPMRC_FILE"
fi

cat >> "$NPMRC_FILE" <<EOF
@humanddev:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${TOKEN}
EOF

echo "Token guardado en $TOKEN_FILE"
echo ".npmrc actualizado en $NPMRC_FILE"
