#!/bin/bash
# Grant DELETE permission on auth database tables
#
# This script grants DELETE permission to the punimtag user on tables in the auth database.
# It requires sudo privileges to run commands as the postgres superuser.
#
# Manual alternative (if script fails):
#   sudo -u postgres psql -d punimtag_auth -c "GRANT DELETE ON TABLE pending_photos TO punimtag;"
#   sudo -u postgres psql -d punimtag_auth -c "GRANT DELETE ON TABLE users TO punimtag;"
#   sudo -u postgres psql -d punimtag_auth -c "GRANT DELETE ON TABLE pending_identifications TO punimtag;"
#   sudo -u postgres psql -d punimtag_auth -c "GRANT DELETE ON TABLE inappropriate_photo_reports TO punimtag;"
#
# Or all at once:
#   sudo -u postgres psql -d punimtag_auth << 'EOF'
#   GRANT DELETE ON TABLE pending_photos TO punimtag;
#   GRANT DELETE ON TABLE users TO punimtag;
#   GRANT DELETE ON TABLE pending_identifications TO punimtag;
#   GRANT DELETE ON TABLE inappropriate_photo_reports TO punimtag;
#   EOF

set -e

echo "🔧 Granting DELETE permission on auth database tables..."

# Check if .env file exists
ENV_FILE=".env"
if [ ! -f "$ENV_FILE" ]; then
    echo "❌ Error: .env file not found"
    exit 1
fi

# Extract DATABASE_URL_AUTH from .env file
AUTH_DB_URL=$(grep "^DATABASE_URL_AUTH=" "$ENV_FILE" | cut -d '=' -f2- | tr -d '"' | tr -d "'")

if [ -z "$AUTH_DB_URL" ]; then
    echo "❌ Error: DATABASE_URL_AUTH not found in .env file"
    exit 1
fi

# Parse the database URL
# Format: postgresql+psycopg2://user:password@host:port/database
# or: postgresql://user:password@host:port/database

# Remove postgresql+psycopg2:// prefix if present
AUTH_DB_URL=${AUTH_DB_URL#postgresql+psycopg2://}
AUTH_DB_URL=${AUTH_DB_URL#postgresql://}

# Extract components
# Split by @ to get user:pass and host:port/db
IFS='@' read -r CREDENTIALS REST <<< "$AUTH_DB_URL"
IFS=':' read -r DB_USER DB_PASS <<< "$CREDENTIALS"

# Extract host, port, and database
IFS='/' read -r HOST_PORT DB_NAME <<< "$REST"
IFS=':' read -r DB_HOST DB_PORT <<< "$HOST_PORT"

# Set defaults
DB_PORT=${DB_PORT:-5432}
DB_HOST=${DB_HOST:-localhost}

echo "📋 Database information:"
echo "   Host: $DB_HOST"
echo "   Port: $DB_PORT"
echo "   Database: $DB_NAME"
echo "   User: $DB_USER"
echo ""

# Grant DELETE permission using psql as postgres superuser
echo "🔐 Granting DELETE permission on auth database tables (requires sudo)..."
sudo -u postgres psql -d "$DB_NAME" << EOF
GRANT DELETE ON TABLE users TO "$DB_USER";
GRANT DELETE ON TABLE pending_photos TO "$DB_USER";
GRANT DELETE ON TABLE pending_identifications TO "$DB_USER";
GRANT DELETE ON TABLE inappropriate_photo_reports TO "$DB_USER";
\q
EOF

if [ $? -eq 0 ]; then
    echo "✅ Successfully granted DELETE permissions to user '$DB_USER'"
else
    echo "❌ Failed to grant permission"
    exit 1
fi


