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

CALLBACK_URL="http://127.0.0.1:1455/auth/callback"
SUCCESS_URL="http://localhost:1455/success"

die() {
	printf 'ERROR: %s\n' "$*" >&2
	exit 1
}

extract_code() {
	local input="$1"

	case "$input" in
		*code=*)
			input="${input#*code=}"
			input="${input%%&*}"
			input="${input%%#*}"
			;;
	esac

	printf '%s' "$input"
}

extract_id_token() {
	local response_file="$1"

	sed -n 's/.*id_token=\([^&[:space:]"'"'"'<>]*\).*/\1/p' "$response_file" |
		tr -d '\r' |
		head -n 1
}

printf 'Codex ChatGPT login helper\n'
printf 'Paste the received code, full callback URL, or query string containing code=...\n'
printf 'Received key: '
IFS= read -r received_key

[ -n "$received_key" ] || die "empty received key"

code="$(extract_code "$received_key")"
[ -n "$code" ] || die "could not extract code"

response_file="$(mktemp)"
trap 'rm -f "$response_file"' EXIT

printf '\nCalling Codex auth callback...\n'
curl -sv -H "Host: localhost" --get --data-urlencode "code=$code" "$CALLBACK_URL" >"$response_file" 2>&1 || {
	cat "$response_file" >&2
	die "callback request failed"
}

id_token="$(extract_id_token "$response_file")"
[ -n "$id_token" ] || {
	cat "$response_file" >&2
	die "could not find id_token in callback response"
}

printf 'id_token received. Completing login...\n'
curl -sv --get --data-urlencode "id_token=$id_token" "$SUCCESS_URL"
printf '\nDone.\n'
