#!/bin/bash
SERVICE_ACCOUNT_KEY_FILE="/opt/openclaw/.openclaw/workspace/google_service_account.json"
FOLDER_ID="1EaS10C6-ozNN0iyZC_pJ_28-SG8EWetG"
SCOPE="https://www.googleapis.com/auth/drive.readonly"

HEADER=$(echo -n '{"alg":"RS256","typ":"JWT"}' | base64 | tr -d '\n=' | tr '/+' '_-')
IAT=$(date +%s)
EXP=$((IAT + 3600))
CLIENT_EMAIL=$(jq -r .client_email "$SERVICE_ACCOUNT_KEY_FILE")
CLAIM_SET=$(jq -n -c --arg email "$CLIENT_EMAIL" --arg scope "$SCOPE" --argjson iat $IAT --argjson exp $EXP '{iss: $email, scope: $scope, aud: "https://www.googleapis.com/oauth2/v4/token", iat: $iat, exp: $exp}')
CLAIM_SET_ENCODED=$(echo -n "$CLAIM_SET" | base64 -w0 | tr -d '=' | tr '/+' '_-')
SIGNED_CONTENT="$HEADER.$CLAIM_SET_ENCODED"
PRIVATE_KEY=$(jq -r .private_key "$SERVICE_ACCOUNT_KEY_FILE")
echo "$PRIVATE_KEY" > /tmp/private_key_drive.pem
SIGNATURE=$(echo -n "$SIGNED_CONTENT" | openssl dgst -sha256 -sign /tmp/private_key_drive.pem | base64 -w0 | tr -d '=' | tr '/+' '_-')
rm /tmp/private_key_drive.pem
JWT="$SIGNED_CONTENT.$SIGNATURE"
TOKEN_RESPONSE=$(curl -s -X POST "https://www.googleapis.com/oauth2/v4/token" -H "Content-Type: application/x-www-form-urlencoded" --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" --data-urlencode "assertion=$JWT")
ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r .access_token)

if [ "$ACCESS_TOKEN" == "null" ] || [ -z "$ACCESS_TOKEN" ]; then
    echo "Failed to get access token: $TOKEN_RESPONSE"
    exit 1
fi

DRIVE_API_ENDPOINT="https://www.googleapis.com/drive/v3/files?q='${FOLDER_ID}'+in+parents"

curl -s -X GET "$DRIVE_API_ENDPOINT" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" > drive_result.json

cat drive_result.json | jq -r '.files[]?.name // .error.message'
