#!/bin/bash

# Replace 'FILE_ID' with the ID of your file
file_id="$1"
# Replace 'output_filename.ext' with the desired name for your downloaded file
output_filename="$2"

echo "Downloading file from Google Drive..."

# Step 1: Get the confirmation token from the download page.
# We save the cookies from the first request to use in the second request.
html=$(curl -s -L -c /tmp/gdrive_cookies.txt "https://drive.google.com/uc?export=download&id=${file_id}")

# Extract the 'confirm' token from the HTML response
# Note: The regex might need to be adjusted if Google changes the page structure.
confirm_token=$(echo "${html}" | grep -oP 'confirm=[a-zA-Z0-9_-]+')

# Check if a token was found
if [[ -z "${confirm_token}" ]]; then
    echo "Error: Could not find confirmation token. The file might be private, or the download URL has changed."
    exit 1
fi

echo "Confirmation token found. Starting download..."

# Step 2: Use the confirmation token and cookies to download the file.
curl -s -L -b /tmp/gdrive_cookies.txt -o "${output_filename}" "https://drive.google.com/uc?export=download&${confirm_token}&id=${file_id}"

# Clean up temporary cookie file
rm /tmp/gdrive_cookies.txt

echo "File '${output_filename}' downloaded successfully."
exit 0
