#!/usr/bin/with-contenv bash

# copy config.json if doesn't exist
[[ ! -f /config/config.json ]] && \
    cp /defaults/config.json /config/config.json

# check for the mysql endpoint for 30 seconds if user is using our env vars
if [ -n "${DB_HOST+x}" ]; then
    END=$((SECONDS+30))
    while [ ${SECONDS} -lt ${END} ]; do
        if /bin/nc -w1 ${DB_HOST} ${DB_PORT} > /dev/null 2>&1; then
            [ ! -z "${RUN}" ] && break
            RUN="RAN"
            # we sleep here again due to first run init on DB containers
            [ ! -f /dbwait.lock ] && sleep 5
        else
            echo "Waiting for Mysql service"
            sleep 1
        fi
        sleep 1
    done
fi

# migration from codimd
if [ -f "/config/codimd.sqlite" ] && [ ! -f "/config/hedgedoc.sqlite" ]; then
    echo "Migrating codimd sqlite db to hedgedoc"
    mv /config/codimd.sqlite /config/hedgedoc.sqlite
fi

# permissions
chown -R abc:abc \
    /config

# set lockfile to avoid DB waits for this specific container
touch /dbwait.lock
