#!/bin/bash

set -e

# Input validation
if [ -z "$1" ]; then
    echo "Usage: $0 <google_drive_share_url>"
    exit 1
fi

URL="$1"
FILEID=$(echo "$URL" | grep -o '[-_a-zA-Z0-9]\{25,\}')

if [ -z "$FILEID" ]; then
    echo "❌ Could not extract file ID from URL."
    exit 1
fi

FILENAME="download_$(date +%s).zip"
COOKIE_FILE=$(mktemp)

# Step 1: Get the initial download page to fetch confirm token
echo "📡 Contacting Google Drive..."
HTML=$(curl -sc "$COOKIE_FILE" "https://drive.google.com/uc?export=download&id=${FILEID}")

CONFIRM=$(echo "$HTML" | grep -o 'confirm=[^&]*' | sed 's/confirm=//')

if [ -z "$CONFIRM" ]; then
    echo "⚠️  No confirmation token found. Trying direct download..."
    curl -Lb "$COOKIE_FILE" \
        "https://drive.google.com/uc?export=download&id=${FILEID}" -o "$FILENAME"
else
    echo "🔐 Using confirmation token: $CONFIRM"
    curl -Lb "$COOKIE_FILE" \
        "https://drive.google.com/uc?export=download&confirm=${CONFIRM}&id=${FILEID}" -o "$FILENAME"
fi

rm -f "$COOKIE_FILE"

# Check if it's actually a zip file
MIME_TYPE=$(file --mime-type -b "$FILENAME")
if [[ "$MIME_TYPE" != "application/zip" ]]; then
    echo "❌ Download failed or file is not a ZIP archive. Detected type: $MIME_TYPE"
    echo "🔎 Try opening $FILENAME manually to check."
    exit 1
fi

# Extract zip
OUTDIR="${FILENAME%.zip}"
mkdir -p "$OUTDIR"
echo "📦 Unzipping to folder: $OUTDIR"
unzip -q "$FILENAME" -d "$OUTDIR"
rm "$FILENAME"

echo "✅ Done! Files are in: $OUTDIR"
