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

DB_VALID=$(php -r 'echo filter_var(getenv("DATABASE_URL"), FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED);')

if [[ ${DATABASE_URL+x} == "" ]] || [[ ${DB_VALID+x} == "NULL" ]]; then
    cat <<-EOF
    ********************************************************
    ********************************************************
    *                                                      *
    *                         !!!!                         *
    *     DATABASE_URL environment variable is not set     *
    *                          OR                          *
    *    DATABASE_URL environment variable is not valid    *
    *                                                      *
    *              Please refer to the README              *
    *                                                      *
    *                                                      *
    ********************************************************
    ********************************************************
EOF
    sleep infinity
fi

# make our folders
mkdir -p \
    /config/www/var/{cache,data,log,packages,plugins,sessions}

rm -rf /app/www/var
ln -s /config/www/var /app/www/var
cp /app/www/config/packages/kimai.yaml /config/kimai.yaml.sample
if [[ ! -f /config/local.yaml ]]; then
    echo '# See https://www.kimai.org/documentation/local-yaml.html' > /config/local.yaml
fi
if [[ ! -L /app/www/config/packages/local.yaml ]]; then
    ln -s /config/local.yaml /app/www/config/packages/local.yaml
fi

# Clear cache on image upgade
if [[ ! -f /dbwait.lock ]];then
    rm -rf /config/www/var/cache/*
fi

DB_HOST=$(php -r 'echo parse_url(getenv("DATABASE_URL"), PHP_URL_HOST);')
DB_PORT=$(php -r 'echo parse_url(getenv("DATABASE_URL"), PHP_URL_PORT) ?? 3306;')

# check for the mysql endpoint
echo "Waiting for DB to be available"
END=$((SECONDS + 30))
while [[ ${SECONDS} -lt ${END} ]]; 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
# set lockfile to avoid DB waits for this specific container
touch /dbwait.lock

lsiown -R abc:abc \
    /config/www

console kimai:install -n
