#!/usr/bin/env bash
# BiznisOS - first install on a live server (Ubuntu, PHP 8.2+, MySQL 8, Composer).
# Run from the project folder as the deploy user:   bash install.sh
# Prepare first: an empty MySQL database and user (DEPLOYMENT.md step 3), and the web server
# pointing at the public/ folder (step 5). This script never overwrites an existing .env.
set -euo pipefail
cd "$(dirname "$0")"

command -v php >/dev/null || { echo "PHP is not installed."; exit 1; }
php -r 'exit(version_compare(PHP_VERSION, "8.2.0", ">=") ? 0 : 1);' || { echo "PHP 8.2 or newer is required."; exit 1; }
command -v composer >/dev/null || { echo "Composer is not installed: https://getcomposer.org/download/"; exit 1; }
for ext in mbstring openssl pdo_mysql gd intl zip bcmath curl; do
  php -m | grep -qi "^$ext$" || { echo "Missing PHP extension: $ext"; exit 1; }
done

echo "== Installing PHP packages"
composer install --no-dev --optimize-autoloader --no-interaction

if [ ! -f .env ]; then
  cp .env.example .env
  php artisan key:generate --force
  echo
  echo "A new .env was created. Fill in the database, mail and APP_URL values"
  echo "(see SETUP_REQUIRED.md), then run this script again."
  exit 0
fi

grep -q '^APP_ENV=production' .env || echo "Warning: APP_ENV is not 'production' in .env."
grep -q '^APP_DEBUG=false' .env   || echo "Warning: APP_DEBUG should be false on a live server."

echo "== Creating database tables"
php artisan migrate --force

echo "== Linking public storage and caching config, routes and views"
php artisan storage:link || true
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "== Setting folder permissions"
chmod -R ug+rwX storage bootstrap/cache
if getent group www-data >/dev/null; then chgrp -R www-data storage bootstrap/cache 2>/dev/null || echo "Run: sudo chgrp -R www-data storage bootstrap/cache"; fi

cat <<'DONE'

Installed. Still to do (DEPLOYMENT.md):
  - Queue worker (supervisor) and the scheduler cron:  * * * * * php artisan schedule:run
  - HTTPS certificate, backups
  - Push alerts (optional): php artisan biznisos:vapid, paste both lines into .env, then php artisan config:cache
  - Open the site, register the first account, then make yourself platform admin:
      UPDATE users SET is_super_admin = 1 WHERE email = 'you@example.com';
DONE
