#!/bin/bash

exec >> $SNAP_DATA/hook.log 2>&1
echo "$(date '+%Y-%m-%d %H:%M:%S') $0: Entering hook"

set -x

# read wekan config
. $SNAP/bin/config

# settings were altered by user, safest way to get them applied is to restart service
# first check if caddy service is enabled
value=$(snapctl get caddy-enabled)
if [ "$value" = "true" ]; then
    # update caddy file
    bind_port=$(snapctl get caddy-bind-port)
    port=$(snapctl get port)
    [ "x" != "x${bind_port}" ] && sed -i 's|proxy / localhost:.* {|proxy / localhost:'"${bind_port}"' {|g' $SNAP_COMMON/Caddyfile
    [ "x" != "x$port" ] && sed -i 's|http://:.*|http://:'"${port}"'|g' $SNAP_COMMON/Caddyfile
    snapctl start --enable ${SNAP_NAME}.caddy 2>&1 || true
    snapctl restart ${SNAP_NAME}.caddy 2>&1 || true
else
    snapctl stop --disable ${SNAP_NAME}.caddy 2>&1 || true
fi

# Database backend selection: mongodb (default) or ferretdb (FerretDB v1, SQLite).
# Only one runs at a time; both bind the same port, so WeKan's MONGO_URL is
# unchanged either way.
database=$(snapctl get database)
disable_mongodb=$(snapctl get disable-mongodb)
if [ "$database" = "ferretdb" ]; then
    # FerretDB selected: stop mongod, start FerretDB.
    snapctl stop --disable ${SNAP_NAME}.mongodb 2>&1 || true
    snapctl start --enable ${SNAP_NAME}.ferretdb 2>&1 || true
    snapctl restart ${SNAP_NAME}.ferretdb 2>&1 || true
else
    # MongoDB selected (default): stop FerretDB; honor disable-mongodb for mongod.
    snapctl stop --disable ${SNAP_NAME}.ferretdb 2>&1 || true
    if [ "$disable_mongodb" = "true" ]; then
        snapctl stop --disable ${SNAP_NAME}.mongodb 2>&1 || true
    else
        snapctl start --enable ${SNAP_NAME}.mongodb 2>&1 || true
        snapctl restart ${SNAP_NAME}.mongodb 2>&1 || true
    fi
fi

# restart all services
snapctl restart ${SNAP_NAME}.wekan 2>&1 || true
