#!/bin/bash

# Script to install Ghostscript for PDF decompression
# Required for handling user-uploaded PDF attachments

echo "======================================"
echo "Installing Ghostscript..."
echo "======================================"

# Check if running as root or with sudo
if [ "$EUID" -ne 0 ]; then 
    echo "This script requires sudo privileges"
    USE_SUDO="sudo"
else
    USE_SUDO=""
fi

# Detect OS type
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
else
    echo "Cannot detect OS type"
    exit 1
fi

# Install based on OS
case $OS in
    ubuntu|debian)
        echo "Detected Ubuntu/Debian system"
        $USE_SUDO apt-get update
        $USE_SUDO apt-get install -y ghostscript
        ;;
    centos|rhel|fedora)
        echo "Detected CentOS/RHEL/Fedora system"
        $USE_SUDO yum install -y ghostscript
        ;;
    *)
        echo "Unsupported OS: $OS"
        echo "Please install Ghostscript manually"
        exit 1
        ;;
esac

# Verify installation
echo ""
echo "======================================"
echo "Verifying installation..."
echo "======================================"

if command -v gs &> /dev/null; then
    echo "✓ Ghostscript installed successfully!"
    echo "Version: $(gs --version)"
    echo ""
    echo "Path: $(which gs)"
else
    echo "✗ Ghostscript installation failed"
    exit 1
fi

# Test basic functionality
echo ""
echo "======================================"
echo "Testing Ghostscript..."
echo "======================================"

TEST_OUTPUT=$(gs --version 2>&1)
if [ $? -eq 0 ]; then
    echo "✓ Ghostscript is working correctly"
else
    echo "✗ Ghostscript test failed"
    exit 1
fi

echo ""
echo "======================================"
echo "Installation Complete!"
echo "======================================"
echo ""
echo "You can now deploy the code changes to use PDF decompression."
echo "Remember to clear Laravel cache:"
echo "  php artisan cache:clear"
echo "  php artisan view:clear"
echo ""
