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

EXTENSION_ID="${1:-alaohbbicffclloghmknhlmfdbobcigc}"
HOST_NAME="org.gdown.nativehost"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUNNER_PATH="$SCRIPT_DIR/.runtime/run-host-macos.sh"
TEMPLATE_PATH="$SCRIPT_DIR/manifest/${HOST_NAME}.json.template"
CHROME_DIR="$HOME/Library/Application Support/Google/Chrome/NativeMessagingHosts"
OUT_PATH="$CHROME_DIR/${HOST_NAME}.json"
NODE_PATH="$(command -v node || true)"

if [[ ! -f "$TEMPLATE_PATH" ]]; then
  echo "template not found: $TEMPLATE_PATH" >&2
  exit 1
fi

if [[ -z "$NODE_PATH" ]]; then
  echo "node not found in current shell PATH" >&2
  exit 1
fi

mkdir -p "$CHROME_DIR"
mkdir -p "$SCRIPT_DIR/.runtime"

cat > "$RUNNER_PATH" <<EOF
#!/usr/bin/env bash
set -euo pipefail
exec "$NODE_PATH" "$SCRIPT_DIR/host.mjs"
EOF

chmod +x "$RUNNER_PATH"

sed \
  -e "s|__ABSOLUTE_HOST_PATH__|$RUNNER_PATH|g" \
  -e "s|__EXTENSION_ID__|$EXTENSION_ID|g" \
  "$TEMPLATE_PATH" > "$OUT_PATH"

echo "installed: $OUT_PATH"
echo "extension id: $EXTENSION_ID"
echo "node path: $NODE_PATH"
