#! /usr/bin/env bash
set -e
SCRIPT_DIR=${SCRIPT_DIR:-"$( cd -- "$( dirname -- "$0" )" &> /dev/null && pwd )"}

SYS_NAME=${1:-${SYS_NAME:?Must supply sysname as 1st argument}}
TOP_DIR="$SCRIPT_DIR/_traefik/dynamic"

# Store the find results in an array
mapfile -d '' -t DELETE < <(find "$TOP_DIR" -maxdepth 1 -mindepth 1 -type l -lname '*_templates/*' -print0)

# If links were found, process and delete them
if [ ${#DELETE[@]} -gt 0 ]; then
    for link in "${DELETE[@]}"; do
        # Get the target of the symbolic link
	target=$(basename $(readlink -f "$link"))
        
        # Delete the link
        rm "$link"
        
        # Report the deleted link and its target
	printf '"%s" (%s) deleted.\n' "$link" "${target##*.}"
    done
else
    echo "No matching symbolic links found to delete."
fi

find "$TOP_DIR/_templates" -maxdepth 1 -mindepth 1 -type f -name "*.${SYS_NAME}" -print0 \
| while IFS= read -r -d '' file; do
    base=$(basename "$file" ".${SYS_NAME}")
    ext="${base##*.}"
    #echo ln -rs "${file#${TOP_DIR}/}" "${base}"
    ln -vrs "${file}" "${TOP_DIR}/${base%${ext}}local.$ext"
done

SECRET_BASE="${SCRIPT_DIR}/_secrets"
SECRETS=(
	"tipi_jwt_secret"
	"tipi_postgres_password"
	"tipi_redis_password"
)
for file in "${SECRETS[@]}"; do
    secret="${SECRET_BASE}/${file}.txt"
	printf '%s secret ' "${file}"
    if [ -s "${secret}" ]; then
		printf 'exists.'
	else
		printf 'generating... '
		curl -s "https://makemeapassword.ligos.net/api/v1/passphrase/plain?pc=1&wc=6&sp=y&maxCh=64" \
		| sed -Ee 's/ /-/g;' > "${secret}"
		printf 'ready.'
	fi
	printf '\n'
done

SECRETS=(
	"traefik_cf_dns_api_token"
)
for file in "${SECRETS[@]}"; do
    secret="${SECRET_BASE}/${file}.txt"
	printf '%s secret ' "${file}"
    if [ -s "${secret}" ]; then
		printf 'exists.'
	else
		printf 'missing!'
	fi
	printf '\n'
done

if [ -r "${SCRIPT_DIR}/.env.local.${SYS_NAME}.dotenv" ]; then
    [ -L "${SCRIPT_DIR}/.env.local" ] && rm "${SCRIPT_DIR}/.env.local"
    ln -srv "${SCRIPT_DIR}/.env.local.${SYS_NAME}.dotenv" "${SCRIPT_DIR}/.env.local"
fi

if [ "$2" == "--setup" ]; then
    "${SCRIPT_DIR}/_bin/rtpctl.d" setup "-vf"
    "${SCRIPT_DIR}/_bin/rtpctl.d" setup "-vf" $HOME/.local/bin/rtpctl
    "${SCRIPT_DIR}/_bin/rtpctl.d" setup "-vf" $HOME/.local/bin/runtipictl
    "${SCRIPT_DIR}/_bin/rtpctl.d" setup "-vf" $HOME/.local/bin/tpc
fi

# vim: set ft=sh expandtab tabstop=4 shiftwidth=4: