#!/usr/bin/with-contenv bash
# shellcheck shell=bash

lsiown abc:abc \
    /config

if [[ "${DB_CONNECTION:=sqlite}" = "sqlite" ]]; then
    if [[ -n "${DB_DATABASE}" ]]; then
        if [[ ! -e "${DB_DATABASE}" ]]; then
            touch "${DB_DATABASE}"
            lsiown abc:abc "${DB_DATABASE}"
        fi
    else
        touch /config/database.sqlite
        if [[ -e "/app/www/database/database.sqlite" && ! -L "/app/www/database/database.sqlite" ]]; then
            rm -rf "/app/www/database/database.sqlite"
        fi
        if [[ ! -L "/app/www/database/database.sqlite" ]]; then
            ln -s "/config/database.sqlite" "/app/www/database/database.sqlite"
        fi
        lsiown abc:abc /app/www/database/database.sqlite
    fi
elif [[ "${DB_CONNECTION}" = "mysql" ]]; then
    echo "Waiting for DB to be available"
    END=$((SECONDS + 30))
    while [[ ${SECONDS} -lt ${END} ]] && [[ -n "${DB_HOST+x}" ]]; do
        if [[ $(/usr/bin/nc -w1 "${DB_HOST}" "${DB_PORT}" | tr -d '\0') ]]; then
            if [[ -n "${RUN}" ]]; then
                break
            fi
            RUN="RAN"
            # we sleep here again due to first run init on DB containers
            if [[ ! -f /dbwait.lock ]]; then
                sleep 5
            fi
        else
            sleep 1
        fi
    done
elif [[ "${DB_CONNECTION}" = "pgsql" ]]; then
    echo "Waiting for DB to be available"
    END=$((SECONDS + 30))
    while [[ ${SECONDS} -lt ${END} ]] && [[ -n "${DB_HOST+x}" ]]; do
        if pg_isready -h "${DB_HOST}" -p "${DB_PORT}" -q; then
            if [[ -n "${RUN}" ]]; then
                break
            fi
            RUN="RAN"
            # we sleep here again due to first run init on DB containers
            if [[ ! -f /dbwait.lock ]]; then
                sleep 5
            fi
        else
            sleep 1
        fi
    done
fi

lsiown -R abc:abc \
    /app/www/bootstrap/cache \
    /app/www/storage

# Check for env file
if [[ ! -f /config/.env ]]; then
    cp /app/www/.env.production /config/.env
fi

# create symlinks
symlinks=( \
/app/www/.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

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

# Build cache
s6-setuidgid abc php /app/www/artisan view:clear --no-ansi -q
s6-setuidgid abc php /app/www/artisan optimize --no-ansi -q

# Migrate database
s6-setuidgid abc php /app/www/artisan migrate --force --no-ansi -q

lsiown -R abc:abc \
    /config
