#!/bin/bash

# --- Configuration ---
# File name of the FileRun distribution ZIP archive
FILERUN_ZIP="FileRun-2024.1.2-PHP-8.1.zip"
# Directories used for persistent data and code
DATA_DIRS=("db_data" "filerun_html" "user_data")
# UID and GID for the www-data user inside the FileRun container (from docker-compose.yml)
CONTAINER_UID_GID="33:33"
# Temporary directory for extraction
TEMP_DIR="./temp_filerun_extract"
# ---------------------

echo "--- FileRun Installation Script ---"

# --- 1. Create and prepare directories ---
echo "1. Creating and ensuring directories exist..."
for dir in "${DATA_DIRS[@]}"; do
    if [ ! -d "$dir" ]; then
        echo "   -> Creating directory: ${dir}/"
        mkdir -p "$dir"
    fi
done

# --- 2. Unzip FileRun distribution and move files ---
if [ -f "${FILERUN_ZIP}" ]; then
    echo "2. Unzipping ${FILERUN_ZIP} into a temporary folder and moving contents to ./filerun_html..."

    # Create temporary directory for extraction
    mkdir -p "$TEMP_DIR"

    # Unzip to temporary folder
    unzip -q "${FILERUN_ZIP}" -d "$TEMP_DIR"
    if [ $? -ne 0 ]; then
        echo "❌ ERROR: Failed to unzip ${FILERUN_ZIP}. Check if 'unzip' is installed or if the file is corrupted."
        rm -rf "$TEMP_DIR"
        exit 1
    fi

    # Move contents from temp to final location (./filerun_html)
    mv "$TEMP_DIR"/* ./filerun_html/

    # Clean up temporary directory
    rm -rf "$TEMP_DIR"
    
    echo "   [SUCCESS] Files extracted and moved to ./filerun_html."
else
    echo "❌ ERROR: File not found: ${FILERUN_ZIP}. Please ensure it is in the current directory."
    exit 1
fi

# --- 3. Set correct ownership for container user (33:33) ---
echo "3. Setting ownership to ${CONTAINER_UID_GID} (www-data) for required FileRun paths..."

# 3a. Set ownership for the FileRun system data directory (mapped from /var/www/html/system/data)
SYSTEM_DATA_PATH="./filerun_html/system/data"
echo "   -> Setting ownership for ${SYSTEM_DATA_PATH}/"
sudo chown -R ${CONTAINER_UID_GID} "${SYSTEM_DATA_PATH}"

# 3b. Set ownership for the user files directory (mapped from /user-files)
USER_DATA_PATH="./user_data"
echo "   -> Setting ownership for ${USER_DATA_PATH}/"
sudo chown -R ${CONTAINER_UID_GID} "${USER_DATA_PATH}"

echo "   [SUCCESS] Ownership set for application use."

# --- 4. Start Docker Compose services ---
echo "4. Starting Docker services..."
docker compose up -d
if [ $? -ne 0 ]; then
    echo "❌ ERROR: Docker Compose failed to start services. Check your docker-compose.yml for errors."
    exit 1
fi
echo "   [SUCCESS] Services started in detached mode."

# --- 5. Verify container status ---
echo "5. Checking FileRun container status..."
# Wait a few seconds for startup
sleep 5
CONTAINER_STATUS=$(docker compose ps -q filerun | xargs docker inspect --format '{{.State.Status}}')

if [ "$CONTAINER_STATUS" == "running" ]; then
    echo "✅ FileRun container is running."
    echo ""
    echo "--- NEXT STEPS ---"
    echo "FileRun is now accessible via Traefik at: https://filerun.rozic-dev.com"
    echo "If you still encounter a 'Database error', the application needs to run its initial setup."
    echo "1. Check the detailed application logs for the specific PHP error:"
    echo "   docker compose logs filerun"
    echo "2. The database initialization (tables/schema) may take a moment."
else
    echo "❌ WARNING: FileRun container status is '$CONTAINER_STATUS'. Check logs for details:"
    echo "   docker compose logs filerun"
fi