#!/bin/sh
set -eu
umask 077

if [ "$#" -ne 1 ]; then
  echo "usage: $0 <go-module-root>" >&2
  exit 2
fi

module_root=$1
[ -f "$module_root/go.mod" ] || {
  echo "Go module root has no go.mod: $module_root" >&2
  exit 2
}

state_dir=$(mktemp -d "${TMPDIR:-/tmp}/cp9-github-user.XXXXXX")
token_file=$state_dir/token
askpass_file=$state_dir/askpass.sh
cleanup() {
  rm -rf "$state_dir"
}
trap cleanup EXIT HUP INT TERM

cat >"$token_file"
chmod 600 "$token_file"
case "$(cat "$token_file")" in
  ghu_*) ;;
  *) echo "GitHub App user token from stdin is invalid" >&2; exit 2 ;;
esac

cat >"$askpass_file" <<'ASKPASS'
#!/bin/sh
case "$1" in
  *Username*github.com*) printf '%s\n' x-access-token ;;
  *Password*github.com*) cat "$CP9_GITHUB_USER_TOKEN_FILE" ;;
  *) exit 1 ;;
esac
ASKPASS
chmod 700 "$askpass_file"

attempt=1
while [ "$attempt" -le 2 ]; do
  if CP9_GITHUB_USER_TOKEN_FILE=$token_file \
    GIT_ASKPASS=$askpass_file \
    GIT_ASKPASS_REQUIRE=force \
    GIT_TERMINAL_PROMPT=0 \
    GOPRIVATE=github.com/tidbcloud/* \
    GONOSUMDB=github.com/tidbcloud/* \
    GONOPROXY=github.com/tidbcloud/* \
    GOPROXY=https://proxy.golang.org,direct \
    go -C "$module_root" mod download; then
    exit 0
  fi
  if [ "$attempt" -eq 1 ]; then
    echo "GitHub user module download failed; retrying once" >&2
  fi
  attempt=$((attempt + 1))
done

echo "GitHub user module download failed after one retry" >&2
exit 1
