#!/bin/bash

# PDF Repair Dependencies Installation Script
# This script installs Ghostscript for PDF repair functionality

echo "=========================================="
echo "PDF Repair Dependencies Installer"
echo "=========================================="
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "Please run as root or with sudo"
    echo "Usage: sudo bash install-pdf-repair.sh"
    exit 1
fi

# Update package lists
echo "Step 1: Updating package lists..."
apt-get update -qq

# Install Ghostscript
echo ""
echo "Step 2: Installing Ghostscript..."
apt-get install -y ghostscript

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

# Create temp directory for PDF processing
echo ""
echo "Step 4: Creating temp directory..."
TEMP_DIR="/var/www/html/blazma/storage/app/temp"
if [ ! -d "$TEMP_DIR" ]; then
    mkdir -p "$TEMP_DIR"
    chmod 777 "$TEMP_DIR"
    chown www-data:www-data "$TEMP_DIR"
    echo "✓ Temp directory created: $TEMP_DIR"
else
    chmod 777 "$TEMP_DIR"
    chown www-data:www-data "$TEMP_DIR"
    echo "✓ Temp directory already exists: $TEMP_DIR"
fi

# Test Ghostscript with a simple command
echo ""
echo "Step 5: Testing Ghostscript..."
if gs -dNOPAUSE -dBATCH -sDEVICE=nullpage -c quit &> /dev/null; then
    echo "✓ Ghostscript is working correctly!"
else
    echo "⚠ Ghostscript test failed, but it may still work"
fi

echo ""
echo "=========================================="
echo "Installation Complete!"
echo "=========================================="
echo ""
echo "Summary:"
echo "  - Ghostscript: Installed (v$GS_VERSION)"
echo "  - Temp Directory: $TEMP_DIR"
echo ""
echo "Your system is now ready to repair encrypted PDFs automatically!"
echo ""
