#!/bin/bash

# Verification Script: Upload Limits and File Type Restrictions
# Tests that the Message Settings properly restrict file uploads
#
# Usage: ./verify-upload-limits.sh [wordpress_url] [admin_username] [admin_password]
#
# Example: ./verify-upload-limits.sh http://localhost:8080 admin password

set -e

# Configuration
WP_URL="${1:-http://localhost:8080}"
ADMIN_USER="${2:-admin}"
ADMIN_PASS="${3:-password}"
AJAX_URL="$WP_URL/wp-admin/admin-ajax.php"
REST_URL="$WP_URL/wp-json/presszone-forum/v1/admin/settings"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Forum Press Zone - Upload Verification${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Step 1: Login and get cookies
echo -e "${YELLOW}Step 1: Logging in as admin...${NC}"
LOGIN_RESPONSE=$(curl -s -c /tmp/fpz_cookies.txt \
    -d "log=$ADMIN_USER" \
    -d "pwd=$ADMIN_PASS" \
    -d "wp-submit=Log+In" \
    -d "redirect_to=$WP_URL/wp-admin/" \
    "$WP_URL/wp-login.php")

if grep -q "wordpress_logged_in" /tmp/fpz_cookies.txt; then
    echo -e "${GREEN}✓ Login successful${NC}"
else
    echo -e "${RED}✗ Login failed${NC}"
    exit 1
fi

# Step 2: Get nonce from admin page
echo -e "${YELLOW}Step 2: Getting nonce...${NC}"
ADMIN_PAGE=$(curl -s -b /tmp/fpz_cookies.txt "$WP_URL/wp-admin/admin.php?page=forum-press-zone")
UPLOAD_NONCE=$(echo "$ADMIN_PAGE" | grep -oP "uploadNonce['\"]:\s*['\"]([^'\"]+)" | head -1 | grep -oP "[a-f0-9]{10}")

if [ -z "$UPLOAD_NONCE" ]; then
    echo -e "${RED}✗ Failed to get upload nonce${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Got upload nonce: $UPLOAD_NONCE${NC}"

# Step 3: Get current settings via REST API
echo -e "${YELLOW}Step 3: Fetching current settings...${NC}"
REST_NONCE=$(echo "$ADMIN_PAGE" | grep -oP "nonce['\"]:\s*['\"]([^'\"]+)" | head -1 | grep -oP "[a-f0-9]{10}")

SETTINGS=$(curl -s -b /tmp/fpz_cookies.txt \
    -H "X-WP-Nonce: $REST_NONCE" \
    "$REST_URL")

echo "$SETTINGS" | python3 -m json.tool > /tmp/fpz_settings.json 2>/dev/null || echo "$SETTINGS" > /tmp/fpz_settings.json

# Extract current limits
IMAGE_LIMIT=$(echo "$SETTINGS" | grep -oP '"image":\s*\K\d+' | head -1)
DOCUMENT_LIMIT=$(echo "$SETTINGS" | grep -oP '"document":\s*\K\d+' | head -1)
ARCHIVE_LIMIT=$(echo "$SETTINGS" | grep -oP '"archive":\s*\K\d+' | head -1)

echo -e "${GREEN}✓ Current limits:${NC}"
echo "  - Images: $(($IMAGE_LIMIT / 1024 / 1024)) MB"
echo "  - Documents: $(($DOCUMENT_LIMIT / 1024 / 1024)) MB"
echo "  - Archives: $(($ARCHIVE_LIMIT / 1024 / 1024)) MB"

# Check enabled categories
CATEGORIES=$(echo "$SETTINGS" | grep -oP '"post_attachment_categories":\s*\[\K[^\]]+')
echo -e "${GREEN}✓ Enabled categories: $CATEGORIES${NC}"
echo ""

# Step 4: Create test files
echo -e "${YELLOW}Step 4: Creating test files...${NC}"
mkdir -p /tmp/fpz_test_files

# Create 1MB test image (JPG)
dd if=/dev/urandom of=/tmp/fpz_test_files/test_1mb.jpg bs=1M count=1 2>/dev/null
echo -e "${GREEN}✓ Created 1MB test image${NC}"

# Create 3MB test image (exceeds typical 2MB limit)
dd if=/dev/urandom of=/tmp/fpz_test_files/test_3mb.jpg bs=1M count=3 2>/dev/null
echo -e "${GREEN}✓ Created 3MB test image${NC}"

# Create 1MB test PDF
dd if=/dev/urandom of=/tmp/fpz_test_files/test_1mb.pdf bs=1M count=1 2>/dev/null
echo -e "${GREEN}✓ Created 1MB test PDF${NC}"

# Create 5MB test ZIP
dd if=/dev/urandom of=/tmp/fpz_test_files/test_5mb.zip bs=1M count=5 2>/dev/null
echo -e "${GREEN}✓ Created 5MB test ZIP${NC}"

# Create 15MB test ZIP (exceeds typical 10MB limit)
dd if=/dev/urandom of=/tmp/fpz_test_files/test_15mb.zip bs=1M count=15 2>/dev/null
echo -e "${GREEN}✓ Created 15MB test ZIP${NC}"
echo ""

# Step 5: Test uploads
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Testing Upload Restrictions${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Test 1: Upload 1MB image (should succeed if images enabled and limit >= 1MB)
echo -e "${YELLOW}Test 1: Upload 1MB JPG image${NC}"
RESPONSE=$(curl -s -b /tmp/fpz_cookies.txt \
    -F "action=presszone_forum_upload_attachment" \
    -F "nonce=$UPLOAD_NONCE" \
    -F "file=@/tmp/fpz_test_files/test_1mb.jpg" \
    "$AJAX_URL")

if echo "$RESPONSE" | grep -q '"success":true'; then
    echo -e "${GREEN}✓ PASS: 1MB image upload succeeded${NC}"
    echo "  Response: $(echo $RESPONSE | head -c 100)..."
elif echo "$RESPONSE" | grep -q "File type not allowed"; then
    echo -e "${YELLOW}⚠ EXPECTED FAIL: Images are disabled in settings${NC}"
elif echo "$RESPONSE" | grep -q "File too large"; then
    echo -e "${YELLOW}⚠ EXPECTED FAIL: File exceeds image size limit${NC}"
else
    echo -e "${RED}✗ UNEXPECTED: $RESPONSE${NC}"
fi
echo ""

# Test 2: Upload 3MB image (should fail if limit < 3MB)
echo -e "${YELLOW}Test 2: Upload 3MB JPG image (should fail if limit < 3MB)${NC}"
RESPONSE=$(curl -s -b /tmp/fpz_cookies.txt \
    -F "action=presszone_forum_upload_attachment" \
    -F "nonce=$UPLOAD_NONCE" \
    -F "file=@/tmp/fpz_test_files/test_3mb.jpg" \
    "$AJAX_URL")

if echo "$RESPONSE" | grep -q "File too large"; then
    echo -e "${GREEN}✓ PASS: 3MB image correctly rejected (exceeds limit)${NC}"
elif echo "$RESPONSE" | grep -q '"success":true'; then
    echo -e "${YELLOW}⚠ Image upload succeeded (limit must be >= 3MB)${NC}"
else
    echo -e "${RED}✗ UNEXPECTED: $RESPONSE${NC}"
fi
echo ""

# Test 3: Upload 1MB PDF (should succeed if documents enabled)
echo -e "${YELLOW}Test 3: Upload 1MB PDF document${NC}"
RESPONSE=$(curl -s -b /tmp/fpz_cookies.txt \
    -F "action=presszone_forum_upload_attachment" \
    -F "nonce=$UPLOAD_NONCE" \
    -F "file=@/tmp/fpz_test_files/test_1mb.pdf" \
    "$AJAX_URL")

if echo "$RESPONSE" | grep -q '"success":true'; then
    echo -e "${GREEN}✓ PASS: 1MB PDF upload succeeded${NC}"
elif echo "$RESPONSE" | grep -q "File type not allowed"; then
    echo -e "${YELLOW}⚠ EXPECTED FAIL: Documents are disabled in settings${NC}"
else
    echo -e "${RED}✗ UNEXPECTED: $RESPONSE${NC}"
fi
echo ""

# Test 4: Upload 5MB ZIP (should succeed if archives enabled and limit >= 5MB)
echo -e "${YELLOW}Test 4: Upload 5MB ZIP archive${NC}"
RESPONSE=$(curl -s -b /tmp/fpz_cookies.txt \
    -F "action=presszone_forum_upload_attachment" \
    -F "nonce=$UPLOAD_NONCE" \
    -F "file=@/tmp/fpz_test_files/test_5mb.zip" \
    "$AJAX_URL")

if echo "$RESPONSE" | grep -q '"success":true'; then
    echo -e "${GREEN}✓ PASS: 5MB ZIP upload succeeded${NC}"
elif echo "$RESPONSE" | grep -q "File type not allowed"; then
    echo -e "${YELLOW}⚠ EXPECTED FAIL: Archives are disabled in settings${NC}"
elif echo "$RESPONSE" | grep -q "File too large"; then
    echo -e "${YELLOW}⚠ EXPECTED FAIL: File exceeds archive size limit${NC}"
else
    echo -e "${RED}✗ UNEXPECTED: $RESPONSE${NC}"
fi
echo ""

# Test 5: Upload 15MB ZIP (should fail if limit < 15MB)
echo -e "${YELLOW}Test 5: Upload 15MB ZIP archive (should fail if limit < 15MB)${NC}"
RESPONSE=$(curl -s -b /tmp/fpz_cookies.txt \
    -F "action=presszone_forum_upload_attachment" \
    -F "nonce=$UPLOAD_NONCE" \
    -F "file=@/tmp/fpz_test_files/test_15mb.zip" \
    "$AJAX_URL")

if echo "$RESPONSE" | grep -q "File too large"; then
    echo -e "${GREEN}✓ PASS: 15MB ZIP correctly rejected (exceeds limit)${NC}"
elif echo "$RESPONSE" | grep -q '"success":true'; then
    echo -e "${YELLOW}⚠ ZIP upload succeeded (limit must be >= 15MB)${NC}"
else
    echo -e "${RED}✗ UNEXPECTED: $RESPONSE${NC}"
fi
echo ""

# Cleanup
echo -e "${YELLOW}Cleaning up test files...${NC}"
rm -rf /tmp/fpz_test_files
rm -f /tmp/fpz_cookies.txt /tmp/fpz_settings.json
echo -e "${GREEN}✓ Cleanup complete${NC}"
echo ""

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Verification Complete${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo -e "${GREEN}All tests completed. Review results above.${NC}"
echo ""
echo -e "${YELLOW}To modify settings:${NC}"
echo "1. Go to: $WP_URL/wp-admin/admin.php?page=forum-press-zone#/settings"
echo "2. Find 'Message Settings' section"
echo "3. Adjust upload limits and file type toggles"
echo "4. Click 'Save Settings'"
echo "5. Re-run this script to verify changes"
