#!/usr/bin/with-contenv bash

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


# create symlinks
symlinks=( \
/opt/hedgedoc/public/docs \
/opt/hedgedoc/public/uploads \
/opt/hedgedoc/public/views \
/opt/hedgedoc/public/default.md 
)
for i in "${symlinks[@]}"; do
    # if config file is present just remove container one and symlink
    [[ -e "$i" && ! -L "$i" && -e /config/"$(basename "$i")" ]] && \
        rm -Rf "$i" && \
        ln -s /config/"$(basename "$i")" "$i"
    # if config file is not present move it before symlinking
    [[ -e "$i" && ! -L "$i" ]] && \
        mv "$i" /config/"$(basename "$i")" && \
        ln -s /config/"$(basename "$i")" "$i"
done


# 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
