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

# copy config.json if doesn't exist
if [[ ! -f /config/config.json ]]; then
    cp /defaults/config.json /config/config.json
fi

# symlink uploads
mkdir -p /config/uploads
rm -rf /app/hedgedoc/public/uploads
ln -s /config/uploads /app/hedgedoc/public/uploads

# check for the mysql endpoint
if [[ -n "${DB_HOST+x}" ]]; 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:-3306}" | 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
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
lsiown -R abc:abc \
    /config

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