#!/bin/bash

# Google OAuth 2.0 Credentials (Replace with your actual credentials)
JSON_KEY_FILE="/home/insuraz1/public_html/_bildr/backup/oauth.json"
CLIENT_ID=$(jq -r '.installed.client_id' "$JSON_KEY_FILE")
CLIENT_SECRET=$(jq -r '.installed.client_secret' "$JSON_KEY_FILE")
TOKEN_URL=$(jq -r '.installed.token_uri' "$JSON_KEY_FILE")
SCOPE="https://www.googleapis.com/auth/drive.file"
DEVICE_URL="https://oauth2.googleapis.com/device/code"

# Step 1: Start the device authorization flow and get user code and device code
start_device_flow() {
    RESPONSE=$(curl -s -X POST \
      --data "client_id=${CLIENT_ID}" \
      --data "scope=${SCOPE}" \
      ${DEVICE_URL})
    echo "$RESPONSE"

    DEVICE_CODE=$(echo $RESPONSE | jq -r '.device_code')
    USER_CODE=$(echo $RESPONSE | jq -r '.user_code')
    VERIFICATION_URL=$(echo $RESPONSE | jq -r '.verification_url')
    INTERVAL=$(echo $RESPONSE | jq -r '.interval')

    echo "Please visit the following URL on another device to approve the request:"
    echo "$VERIFICATION_URL"
    echo "Enter the following code when prompted: $USER_CODE"
    echo "Waiting for authorization..."
}

# Step 2: Poll for the access token using the device code
poll_for_token() {
    while true; do
        TOKEN="/home/insuraz1/public_html/_bildr/backup/token.json"
        curl -s -X POST \
          --data "client_id=${CLIENT_ID}" \
          --data "client_secret=${CLIENT_SECRET}" \
          --data "device_code=${DEVICE_CODE}" \
          --data "grant_type=urn:ietf:params:oauth:grant-type:device_code" \
        ${TOKEN_URL} > "$TOKEN"       

        ACCESS_TOKEN=$(jq -r '.access_token' "$TOKEN")
        REFRESH_TOKEN=$(jq -r '.refresh_token' "$TOKEN")
        ERROR=$(jq -r '.error'  "$TOKEN")

        if [ "$ACCESS_TOKEN" != "null" ]; then
            echo "Authorization successful!"
            echo "Access Token: $ACCESS_TOKEN"
            echo "Refresh Token: $REFRESH_TOKEN"
            break
        elif [ "$ERROR" == "authorization_pending" ]; then
            echo "Authorization pending. Retrying in $INTERVAL seconds..."
        elif [ "$ERROR" == "slow_down" ]; then
            INTERVAL=$((INTERVAL + 5))
            echo "Slow down requested. Retrying in $INTERVAL seconds..."
        else
            echo "Error: $ERROR"
            exit 1
        fi

        sleep $INTERVAL
    done
}

# Main Process

# 1. Start the device flow
start_device_flow

# 2. Poll for token authorization
poll_for_token
