#! /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

