#!/bin/bash
# BookStack Deployment Script
# Service 3/5 - docs.firefrostgaming.com

set -e
echo "=== BookStack Deployment Starting ==="
date

# Update and install PHP
apt-get update
apt-get install -y php8.3-cli php8.3-fpm php8.3-mysql php8.3-gd php8.3-mbstring php8.3-xml php8.3-curl php8.3-zip php8.3-intl mysql-server

# Install Composer
if [ ! -f /usr/local/bin/composer ]; then
    curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
fi

# Database setup
mysql -e "CREATE DATABASE IF NOT EXISTS bookstack_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -e "CREATE USER IF NOT EXISTS 'bookstack_user'@'localhost' IDENTIFIED BY 'FirefrostBookStack2026!';"
mysql -e "GRANT ALL PRIVILEGES ON bookstack_db.* TO 'bookstack_user'@'localhost';"
mysql -e "FLUSH PRIVILEGES;"

# Download BookStack
cd /var/www
git clone https://github.com/BookStackApp/BookStack.git --branch release --single-branch bookstack || true
cd bookstack
export COMPOSER_ALLOW_SUPERUSER=1
composer install --no-dev --no-plugins

# Configure
cp .env.example .env
sed -i "s|APP_URL=.*|APP_URL=https://docs.firefrostgaming.com|g" .env
sed -i "s|DB_DATABASE=.*|DB_DATABASE=bookstack_db|g" .env
sed -i "s|DB_USERNAME=.*|DB_USERNAME=bookstack_user|g" .env
sed -i "s|DB_PASSWORD=.*|DB_PASSWORD=FirefrostBookStack2026!|g" .env
php artisan key:generate --force
php artisan migrate --force

# Permissions
chown -R www-data:www-data /var/www/bookstack
chmod -R 755 /var/www/bookstack

echo "=== Deployment Complete ==="
