#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
ACCESS_SERVICE="${KLING_KEYCHAIN_ACCESS_SERVICE:-daarion.kling.access_key}"
SECRET_SERVICE="${KLING_KEYCHAIN_SECRET_SERVICE:-daarion.kling.secret_key}"

if [ -z "${KLING_ACCESS_KEY:-}" ]; then
  read -r -s -p "KLING access key: " KLING_ACCESS_KEY
  echo
fi
if [ -z "${KLING_SECRET_KEY:-}" ]; then
  read -r -s -p "KLING secret key: " KLING_SECRET_KEY
  echo
fi

if [ -z "${KLING_ACCESS_KEY}" ] || [ -z "${KLING_SECRET_KEY}" ]; then
  echo "[aurora-kling] both keys are required"
  exit 1
fi

security add-generic-password -U -a "${USER}" -s "${ACCESS_SERVICE}" -w "${KLING_ACCESS_KEY}" >/dev/null
security add-generic-password -U -a "${USER}" -s "${SECRET_SERVICE}" -w "${KLING_SECRET_KEY}" >/dev/null

echo "[aurora-kling] stored in keychain services:"
echo "  - ${ACCESS_SERVICE}"
echo "  - ${SECRET_SERVICE}"

"${ROOT_DIR}/launchd/install-launchd.sh"

echo "[aurora-kling] aurora launchd restarted with keychain-backed kling credentials"
