#!/usr/bin/env bash
# Overlay the custom AGS Account files onto the scaffolded Laravel
# install at /var/www/html/account, then migrate + seed.
set -e

cd /var/www/html/account

# Remove any default Laravel-shipped migrations that would clash with our
# canonical ones (we ship our own users + sessions + cache + jobs).
echo "=== Removing default scaffold migrations ==="
rm -f database/migrations/0001_01_01_000000_create_users_table.php
ls database/migrations/

echo ""
echo "=== Running migrations ==="
php artisan migrate --force 2>&1 | tail -25

echo ""
echo "=== Seeding (ClientApp + Pamela) ==="
php artisan db:seed --force 2>&1 | tail -10

echo ""
echo "=== Ownership + perms ==="
chown -R www-data:www-data /var/www/html/account
chmod -R 775 storage bootstrap/cache

echo ""
echo "=== Caches ==="
php artisan config:cache 2>&1 | tail -1
php artisan route:cache 2>&1 | tail -1
php artisan view:cache 2>&1 | tail -1

echo ""
echo "=== Table sanity ==="
DBPASS=$(grep ^DB_PASSWORD /var/www/html/mathapi/.env | cut -d= -f2-)
mysql -uroot -p"$DBPASS" account -Nse "SELECT TABLE_NAME, TABLE_ROWS FROM information_schema.tables WHERE table_schema='account' ORDER BY TABLE_NAME;" 2>/dev/null

echo ""
echo "=== Apps registered ==="
mysql -uroot -p"$DBPASS" account -e "SELECT id, slug, name, color, launch_url, use_magic_link FROM client_apps;" 2>/dev/null
