#!/usr/bin/env bash
# Explicitly copies the per-install loopback token into one app-owned sandbox
# directory. This is a separate consent step from installing host integration.
set -euo pipefail

readonly PREFIX="${TRACKSELF_HOST_INTEGRATION_PREFIX:-$HOME/.local/lib/trackself-host-integration}"
readonly TOKEN_FILE="$PREFIX/credential/auth-token"
readonly OWNER_MARKER_CONTENT='trackself-host-integration'

[[ $# -eq 1 ]] || {
  echo "usage: $0 ABSOLUTE_APP_CREDENTIAL_DIRECTORY" >&2
  exit 2
}
readonly DESTINATION="$1"
[[ "$DESTINATION" = /* ]] || {
  echo 'app credential directory must be absolute' >&2
  exit 2
}
[[ ! "$DESTINATION" =~ [[:cntrl:]] ]] || {
  echo 'app credential directory must not contain control characters' >&2
  exit 2
}
[[ -f "$PREFIX/.trackself-host-integration-owner" &&
   "$(<"$PREFIX/.trackself-host-integration-owner")" == "$OWNER_MARKER_CONTENT" &&
   -f "$TOKEN_FILE" && ! -L "$TOKEN_FILE" ]] || {
  echo "owned Trackself host integration is not installed at $PREFIX" >&2
  exit 1
}
[[ "$(stat -c '%u' "$TOKEN_FILE")" == "$(id -u)" &&
   "$(stat -c '%a' "$TOKEN_FILE")" == 600 ]] || {
  echo 'installed loopback token must be owned by the current user with mode 600' >&2
  exit 1
}
token="$(<"$TOKEN_FILE")"
[[ "$token" =~ ^[0-9a-f]{64}$ ]] || {
  echo 'installed loopback token is invalid' >&2
  exit 1
}
readonly DESTINATION_TOKEN="$DESTINATION/auth-token"
readonly DESTINATION_MARKER="$DESTINATION/.trackself-host-integration-owner"
if [[ -e "$DESTINATION_TOKEN" ]] &&
   [[ ! -f "$DESTINATION_MARKER" ||
      "$(<"$DESTINATION_MARKER")" != "$OWNER_MARKER_CONTENT" ]]; then
  echo "refusing to replace unowned client credential: $DESTINATION_TOKEN" >&2
  exit 1
fi

install -d -m700 "$DESTINATION"
readonly STAGED_TOKEN="$DESTINATION/.auth-token.new.$$"
trap 'rm -f "$STAGED_TOKEN"' EXIT
install -m600 "$TOKEN_FILE" "$STAGED_TOKEN"
mv -f "$STAGED_TOKEN" "$DESTINATION_TOKEN"
printf '%s\n' "$OWNER_MARKER_CONTENT" > "$DESTINATION_MARKER"
chmod 600 "$DESTINATION_MARKER"
trap - EXIT
echo "Paired Trackself host integration with $DESTINATION"
