#!/bin/bash
# Google OAuth Token Refresh Utility (Shell version)
# Reads credentials from /root/.clawdbot/google-oauth.json
# Refreshes access_token using refresh_token
# Updates the JSON file and prints new access_token

set -e

CREDENTIALS_FILE="/root/.clawdbot/google-oauth.json"

# Check if credentials file exists
if [ ! -f "$CREDENTIALS_FILE" ]; then
    echo "Error: Credentials file not found at $CREDENTIALS_FILE" >&2
    exit 1
fi

# Read credentials from JSON file
CLIENT_ID=$(jq -r '.client_id' "$CREDENTIALS_FILE")
CLIENT_SECRET=$(jq -r '.client_secret' "$CREDENTIALS_FILE")
REFRESH_TOKEN=$(jq -r '.refresh_token' "$CREDENTIALS_FILE")

if [ -z "$CLIENT_ID" ] || [ -z "$CLIENT_SECRET" ] || [ -z "$REFRESH_TOKEN" ]; then
    echo "Error: Missing required credentials in JSON file" >&2
    exit 1
fi

# Make POST request to refresh token
RESPONSE=$(curl -s -X POST https://oauth2.googleapis.com/token \
    -d "client_id=$CLIENT_ID" \
    -d "client_secret=$CLIENT_SECRET" \
    -d "refresh_token=$REFRESH_TOKEN" \
    -d "grant_type=refresh_token")

# Check if curl was successful
if [ $? -ne 0 ]; then
    echo "Error: Failed to make request to Google OAuth API" >&2
    exit 1
fi

# Extract new access_token from response
NEW_ACCESS_TOKEN=$(echo "$RESPONSE" | jq -r '.access_token')

if [ "$NEW_ACCESS_TOKEN" = "null" ] || [ -z "$NEW_ACCESS_TOKEN" ]; then
    echo "Error: Failed to get new access_token from response:" >&2
    echo "$RESPONSE" >&2
    exit 1
fi

# Update the JSON file with new access_token
# Create a temporary file for the update
TEMP_FILE=$(mktemp)
jq --arg token "$NEW_ACCESS_TOKEN" '.access_token = $token' "$CREDENTIALS_FILE" > "$TEMP_FILE"

# Check if jq was successful
if [ $? -eq 0 ]; then
    mv "$TEMP_FILE" "$CREDENTIALS_FILE"
    echo "Successfully updated $CREDENTIALS_FILE with new access_token"
else
    echo "Error: Failed to update JSON file" >&2
    rm -f "$TEMP_FILE"
    exit 1
fi

# Print the new access_token
echo "New access_token:"
echo "$NEW_ACCESS_TOKEN"