#!/command/with-contenv bash

# Exit on error
set -e

echo ""
echo "🐇  Configuring Speedtest Tracker..."
echo ""

# Fix permissions
echo "🔒  Fixing app path file permissions..."
chmod -R 755 /config
chown -R webuser:webgroup /config
chmod -R 755 $WEBUSER_HOME/storage
chown -R webuser:webgroup $WEBUSER_HOME/storage
echo "✅  Permissions fixed."
echo ""

# Build cache
echo "🧹  Clearing any previous caches..."
s6-setuidgid webuser php $WEBUSER_HOME/artisan optimize:clear --no-ansi -q
echo "✅  Cache cleared."
echo ""

if [ ${DB_CONNECTION:="sqlite"} = "sqlite" ]; then
    # create symlinks
    echo "🔗  Creating database symlink..."
    symlinks=( \
    /var/www/html/database/database.sqlite \
    )

    for i in "${symlinks[@]}"
    do
        if [[ -e "$i" && ! -L "$i" ]]; then
            rm -rf "$i"
        fi
        if [[ ! -L "$i" ]]; then
            ln -s /config/"$(basename "$i")" "$i"
        fi
    done

    echo "✅  Database symlink created."
    echo ""
fi

# Check for env file
if [ ! -f /config/.env ]; then
    echo "🙄  Environment file not found, creating..."
    s6-setuidgid webuser cp $WEBUSER_HOME/.env.production /config/.env
    echo "✅  Environment file created."
else
    echo "✅  Environment file exists."
fi

echo ""

# create symlinks
echo "🔗  Creating symlinks for config and log files..."
symlinks=( \
/var/www/html/.env \
)

for i in "${symlinks[@]}"
do
    if [[ -e "$i" && ! -L "$i" ]]; then
        rm -rf "$i"
    fi
    if [[ ! -L "$i" ]]; then
        ln -s /config/"$(basename "$i")" "$i"
    fi
done

echo "✅  Symlinks created."
echo ""

# Check for app key
if [ ! ${APP_KEY} ]; then
    if grep -E "APP_KEY=[0-9A-Za-z:+\/=]{1,}" $WEBUSER_HOME/.env > /dev/null; then
        echo "✅  An application key exists."
    else
        echo "⏳  Generating an application key..."
        export APP_KEY=$(s6-setuidgid webuser php $WEBUSER_HOME/artisan key:generate --show)
        echo "⚠️  An application key was generated at start up, no environment variable was set."
        echo "👀  To set an application key that persists, read the docs: https://docs.speedtest-tracker.dev/"
    fi
else
    echo "✅  An application key environment variable exists."
fi

echo ""

# Build cache
echo "💰  Building the cache..."
s6-setuidgid webuser php $WEBUSER_HOME/artisan view:clear --no-ansi -q
s6-setuidgid webuser php $WEBUSER_HOME/artisan optimize --no-ansi -q
echo "✅  Cache set."
echo ""

# Migrate database
echo "🚛  Migrating the database..."
s6-setuidgid webuser php $WEBUSER_HOME/artisan migrate --force --no-ansi -q
echo "✅  Database migrated."
echo ""

# App install done, show a message
echo "✅  All set, Speedtest Tracker started."
echo ""
