default:
    @just --list

# XAMXAM Justfile

# ============================================================================
# Development
# ============================================================================

[group('dev')]
setup:
    @bash scripts/setup-dev.sh

[group('dev')]
serve: migrate
    @xdg-open http://127.0.0.1:8000 &
    @xdg-open http://127.0.0.1:8000/admin/ &
    @php \
        -d upload_max_filesize=512M \
        -d post_max_size=520M \
        -d memory_limit=256M \
        -d max_execution_time=300 \
        -d max_input_time=300 \
        -S 127.0.0.1:8000 -t app/public/ app/router.php 2>&1 \
        | stdbuf -oL grep -Ev '(Accepted|Closing|live-reload\.php|assets/|favicon)'

[group('dev')]
stop:
    @pkill -f "php -S 127.0.0.1:8000" 2>/dev/null && echo "stopped" || echo "no server running"

[group('dev')]
logs:
    @tail -n 20 error.log 2>/dev/null || echo "no error log"

# ============================================================================
# Deploy
# ============================================================================

[group('deploy')]
deploy:
    # Main deploy (code + assets) then run any pending DB migrations
    rsync -vur --progress --delete \
        --chown="www-data:xamxam" \
        --exclude 'vendor' \
        --exclude 'tests' \
        --exclude '*.md' \
        --exclude '.git*' \
        --exclude '.jj' \
        --exclude '.claude' \
        --exclude '.pi' \
        --exclude '.DS_Store' \
        --exclude '.env' \
        --exclude 'storage/xamxam.db' \
        --exclude 'storage/theses' \
        --exclude 'storage/covers' \
        --exclude 'storage/backup_*' \
        --exclude 'storage/cache/*' \
        --exclude 'storage/maintenance.flag' \
        --exclude 'storage/fixtures' \
        --exclude 'storage/docs' \
        --exclude 'var/cache/*' \
        --exclude 'var/logs/*' \
        app/ xamxam:/var/www/xamxam/
    ssh xamxam "mkdir -p /var/www/xamxam/var/{cache,logs,tmp}"
    ssh xamxam "cd /var/www/xamxam && php migrations/run.php /var/www/xamxam/storage/xamxam.db"
    # Sync .env separately (excluded above to avoid accidental overwrite on subsequent deploys)
    @just deploy-env

[group('deploy')]
deploy-env:
	#!/usr/bin/env bash
	set -euo pipefail
	# Upload app/.env only if it exists locally; never overwrites a remote .env that already has APP_KEY.
	if [ ! -f app/.env ]; then
		echo "WARNING: app/.env not found locally — skipping."
		exit 0
	fi
	if ssh xamxam '[ -f /var/www/xamxam/.env ]'; then
		echo "Remote .env already exists — skipping to avoid overwriting key."
		echo "Run 'just reencrypt-password' if you rotated APP_KEY."
	else
		rsync -v --progress app/.env xamxam:/var/www/xamxam/.env
		ssh xamxam "chmod 640 /var/www/xamxam/.env && chown www-data:xamxam /var/www/xamxam/.env"
		echo ".env uploaded."
	fi

[group('deploy')]
reencrypt-password new_key_b64="":
	#!/usr/bin/env bash
	set -euo pipefail
	# Re-encrypt the SMTP password in the remote DB after rotating APP_KEY.
	# Usage:
	#   1. Generate a new key:  php -r "echo base64_encode(random_bytes(32));"
	#   2. Run:                 just reencrypt-password <new_base64_key>
	#   3. Update app/.env locally with the new key, then run: just deploy-env
	if [ -z "{{new_key_b64}}" ]; then
		echo "Usage: just reencrypt-password <new_base64_key>"
		echo "Generate a key: php -r \"echo base64_encode(random_bytes(32));\""
		exit 1
	fi
	# Run the re-encryption script on the server using the current key (from remote .env)
	# and the supplied new key.
	ssh xamxam "php /var/www/xamxam/scripts/reencrypt-smtp-password.php '{{new_key_b64}}' /var/www/xamxam/storage/xamxam.db"

[group('deploy')]
deploy-db:
    @ssh xamxam '[ ! -f /var/www/xamxam/storage/xamxam.db ]' || (echo "ERROR: remote database already exists. Remove it manually if you intend to overwrite." && exit 1)
    rsync -v --progress app/storage/xamxam.db xamxam:/var/www/xamxam/storage/xamxam.db
    ssh xamxam "chown www-data:xamxam /var/www/xamxam/storage/xamxam.db && chmod 660 /var/www/xamxam/storage/xamxam.db"

[group('deploy')]
deploy-script script_name:
    # Generic script deployer (e.g., just deploy-script setup-server)
    rsync -v scripts/{{script_name}}.sh xamxam:/tmp/{{script_name}}.sh
    @echo ""
    @echo "Script uploaded. SSH into the server and run:"
    @echo ""
    @echo "  sudo DEPLOY_USER=\$USER bash /tmp/{{script_name}}.sh"
    @echo ""

# ============================================================================
# Testing
# ============================================================================

[group('test')]
test:
    # Run all tests. To run a subset, use:
    #   php app/tests/Unit/DatabaseTest.php
    #   php app/tests/Integration/SearchTest.php
    @php app/tests/run-tests.php

[group('test')]
lint-biome:
    @biome lint app/public/assets/js/

[group('test')]
phpstan:
    @vendor/bin/phpstan analyse --memory-limit=512M

[group('test')]
cs-check:
    @vendor/bin/php-cs-fixer check --no-interaction

[group('test')]
cs-fix:
    @vendor/bin/php-cs-fixer fix --no-interaction

[group('test')]
syntax:
    @find app/ -name '*.php' -exec php -l {} \; 2>/dev/null | grep -v 'No syntax errors' || true
    @echo '✅ Syntax OK'

# ============================================================================
# Database
# ============================================================================

[group('database')]
migrate:
    @echo "Running migrations…"
    @bash scripts/migrate.sh

[group('database')]
init-db:
    @sqlite3 app/storage/xamxam.db < app/storage/schema.sql
    @sqlite3 app/storage/xamxam.db "SELECT COUNT(*) || ' tables' FROM sqlite_master WHERE type='table';"

[group('database')]
reset-db:
    @rm -f app/storage/xamxam.db
    @just init-db

[group('database')]
query:
    @sqlite3 app/storage/xamxam.db

[group('database')]
backup:
    @sqlite3 app/storage/xamxam.db .dump > app/storage/backup_$(date +%Y%m%d_%H%M%S).sql

# ============================================================================
# Utils
# ============================================================================

[group('utils')]
clean:
    @rm -f app/error.log
    @rm -rf app/storage/cache/rate_limit/*
    @rm -f /tmp/xamxam-*.log /tmp/xamxam-*.pid
