#!/usr/bin/env sh
set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$SCRIPT_DIR"

if [ ! -f "opencode.json" ]; then
  echo "Missing opencode.json in $(pwd)."
  echo "Put opencode.json in the same folder as this script."
  exit 1
fi

printf "Enter your API key: "
read -r API_KEY
if [ -z "$API_KEY" ]; then
  echo "API key is empty. Aborting."
  exit 1
fi

TARGET_DIR="$HOME/.config/opencode"
mkdir -p "$TARGET_DIR"

sed -E "s/(\"apiKey\"[[:space:]]*:[[:space:]]*\")[^\"]*(\")/\\1$API_KEY\\2/" opencode.json > "$TARGET_DIR/opencode.json"

echo "Wrote config to $TARGET_DIR/opencode.json"
