#!/bin/bash

# Authorization Header Diagnostic Tool
# Helps identify and fix Authorization header stripping issues

set -e

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

echo -e "${GREEN}=== Authorization Header Diagnostic Tool ===${NC}\n"

# Get the server URL
read -p "Enter your server URL (e.g., https://dev.globalgala.com): " SERVER_URL
SERVER_URL="${SERVER_URL%/}"  # Remove trailing slash

echo -e "\n${YELLOW}Step 1: Testing diagnostic endpoint...${NC}"
echo -e "${YELLOW}NOTE: debug-headers.php has been moved to scripts/debug/ for security (2025-11-08).${NC}"
echo -e "${YELLOW}For testing, temporarily upload scripts/debug/debug-headers.php to web root.${NC}"

# Test the diagnostic endpoint
RESPONSE=$(curl -s -H "Authorization: Bearer test-token-123" "$SERVER_URL/debug-headers.php")

if [ -z "$RESPONSE" ]; then
    echo -e "${RED}ERROR: No response from server.${NC}"
    echo -e "${YELLOW}To test, upload scripts/debug/debug-headers.php to your web root temporarily.${NC}"
    echo -e "${YELLOW}REMEMBER: Remove it after testing (security risk if left accessible).${NC}"
    exit 1
fi

echo "$RESPONSE" > /tmp/auth-diagnostic.json
echo -e "${GREEN}✓ Response received${NC}"

# Parse the response
PHP_HANDLER=$(echo "$RESPONSE" | grep -o '"php_sapi_name":"[^"]*"' | cut -d'"' -f4)
HTTP_AUTH=$(echo "$RESPONSE" | grep -o '"\$_SERVER\[HTTP_AUTHORIZATION\]":"[^"]*"' | cut -d'"' -f4)

echo -e "\n${YELLOW}Step 2: Analyzing results...${NC}"
echo "PHP Handler: $PHP_HANDLER"
echo "HTTP_AUTHORIZATION value: $HTTP_AUTH"

# Determine the issue
if [ "$HTTP_AUTH" == "NOT FOUND" ] || [ -z "$HTTP_AUTH" ]; then
    echo -e "\n${RED}⚠ ISSUE DETECTED: Authorization header is NOT reaching PHP${NC}"

    echo -e "\n${YELLOW}Recommended Fix:${NC}"

    case "$PHP_HANDLER" in
        *"cgi-fcgi"*|*"fpm-fcgi"*)
            echo "Your server uses FastCGI/PHP-FPM"
            echo ""
            echo "Add this to your .htaccess file (after 'RewriteEngine On'):"
            echo ""
            echo -e "${GREEN}"
            cat <<'EOF'
# FastCGI Authorization Header Fix
<IfModule mod_rewrite.c>
    RewriteCond %{HTTP:Authorization} ^(.+)$
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<IfModule mod_fcgid.c>
    FcgidPassHeader Authorization
</IfModule>

<IfModule mod_setenvif.c>
    SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
</IfModule>
EOF
            echo -e "${NC}"
            ;;

        *"litespeed"*)
            echo "Your server uses LiteSpeed"
            echo ""
            echo "Add this to your .htaccess file:"
            echo ""
            echo -e "${GREEN}"
            cat <<'EOF'
# LiteSpeed Authorization Header Fix
<IfModule LiteSpeed>
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%1]
</IfModule>
EOF
            echo -e "${NC}"
            ;;

        *"apache2handler"*)
            echo "Your server uses Apache mod_php (DSO)"
            echo ""
            echo "This should work with standard .htaccess rules."
            echo "The issue might be in your virtual host configuration."
            echo ""
            echo "Check /etc/apache2/sites-available/ for CGIPassAuth Off"
            ;;

        *)
            echo "Unknown or generic PHP handler: $PHP_HANDLER"
            echo ""
            echo "Try the NUCLEAR OPTION from .htaccess.fixes"
            ;;
    esac

    echo -e "\n${YELLOW}Alternative Solutions:${NC}"
    echo "1. Enable CGIPassAuth in Apache config:"
    echo "   CGIPassAuth On"
    echo ""
    echo "2. Pass via query parameter (temporary workaround):"
    echo "   Accept token as ?token=xxx and set Authorization header in PHP"
    echo ""
    echo "3. Use custom header name (e.g., X-API-Token) that won't be stripped"

else
    echo -e "\n${GREEN}✓ SUCCESS: Authorization header is reaching PHP correctly${NC}"
    echo "Value received: $HTTP_AUTH"
    echo ""
    echo "The Authorization header is NOT the problem."
    echo "Check your Laravel application for other issues:"
    echo "  - Middleware configuration"
    echo "  - JWT parsing logic"
    echo "  - Token validation"
fi

echo -e "\n${YELLOW}Full diagnostic output saved to: /tmp/auth-diagnostic.json${NC}"
echo "Review it for additional details about server configuration."

echo -e "\n${YELLOW}Next Steps:${NC}"
echo "1. Apply the recommended .htaccess fix"
echo "2. Test again with: curl -H 'Authorization: Bearer test-token-123' $SERVER_URL/debug-headers.php"
echo "   (Remember: debug-headers.php must be in web root for testing, remove after)"
echo "3. Verify \$_SERVER[HTTP_AUTHORIZATION] is no longer 'NOT FOUND'"
echo "4. Test your Laravel API endpoint with a real JWT token"
echo "5. IMPORTANT: Remove debug-headers.php from web root after testing (security)"
