#!/bin/bash

set -e

function wait_for_db {
    while true; do
        echo "waiting for Database init"
        php -r 'new PDO("mysql:host='$DB_HOST';dbname='$DB_DATABASE'", "'$DB_USERNAME'", "'$DB_PASSWORD'");' > /dev/null && return 0
        sleep 1
    done
}

mkdir -p /app/packages/laravel-nami/.cookies || true
mkdir -p /app/storage/app/public || true
chown -R www-data:www-data /app/packages/laravel-nami/.cookies
chown -R www-data:www-data /app/storage/app

if [ $APP_KEY = "YOUR_APP_KEY" ]; then
    echo "----------------------- Keinen APP KEY gefunden. Key wird generiert:    $(su www-data -c 'php artisan key:generate --show')   ----------------------- Füge diesen Key als APP_KEY ein ---------------------"
    exit 1
fi

if [ $1 == "horizon" ]; then
    wait_for_db
    su www-data -c 'php artisan horizon'
fi

if [ $1 == "app" ]; then
    # --------------------------- ensure appkey is set ----------------------------
    wait_for_db
    php -r '$connection = new PDO("mysql:host='$DB_HOST';dbname='$DB_DATABASE'", "'$DB_USERNAME'", "'$DB_PASSWORD'"); $connection->query("DESCRIBE migrations");' > /dev/null || php artisan migrate --seed --force
    su www-data -c 'php artisan migrate --force'
    php artisan scout:sync-index-settings
    php-fpm -F -R -O
fi


if [ $1 == "schedule" ]; then
    wait_for_db
    while true; do
        su www-data -c 'php artisan schedule:run -n'
        sleep 60
    done
fi