#!/bin/bash

set -e

# Check for URL input
if [ -z "$1" ]; then
    echo "Usage: $0 <google_drive_share_url>"
    exit 1
fi

# Extract File ID from the URL
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

# Generate temporary names
FILENAME="download_$(date +%s).zip"
COOKIE_FILE=$(mktemp)

# Fetch confirmation token (if needed)
CONFIRM=$(curl -sc "$COOKIE_FILE" "https://drive.google.com/uc?export=download&id=${FILEID}" | \
          grep -o 'confirm=[^&]*' | sed 's/confirm=//')

# Download the file using confirmation token if required
echo "⬇️  Downloading file..."
curl -Lb "$COOKIE_FILE" \
     "https://drive.google.com/uc?export=download&confirm=${CONFIRM}&id=${FILEID}" \
     -o "$FILENAME"

rm -f "$COOKIE_FILE"

# Make sure it's a zip
if ! file "$FILENAME" | grep -q "Zip archive"; then
    echo "❌ File downloaded is not a zip archive."
    echo "Saved as: $FILENAME"
    exit 1
fi

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

# Cleanup
rm "$FILENAME"
echo "✅ Done! Files are in: $OUTDIR"
