#! /bin/sh
# Runs inside the mailcow-conf-sync helper pod.  Updates the config PVC
# mounted at /conf in place:
#
#   - files in /tmp/changes that already exist: overwrite content only,
#     keeping owner and mode,
#   - new files: create, owned like their parent directory,
#   - files listed in /tmp/deleted-files.txt: delete.
set -eu

conf=/conf
changes=/tmp/changes

cd "$changes"
find . -type f | while read -r f; do
    f=${f#./}
    dst=$conf/$f
    if [ -e "$dst" ]; then
        cat "$f" >"$dst"
        echo "updated  $f"
    else
        dir=$(dirname "$dst")
        if [ ! -d "$dir" ]; then
            parent=$dir
            while [ ! -d "$parent" ]; do parent=$(dirname "$parent"); done
            owner=$(stat -c %u:%g "$parent")
            mkdir -p "$dir"
            # Hand every newly created directory to the existing parent's owner.
            d=$dir
            while [ "$d" != "$parent" ]; do chown "$owner" "$d"; d=$(dirname "$d"); done
        fi
        cp "$f" "$dst"
        chown "$(stat -c %u:%g "$dir")" "$dst"
        chmod "$(stat -c %a "$f")" "$dst"
        echo "created  $f"
    fi
done

while read -r f; do
    if [ -e "$conf/$f" ]; then
        rm "$conf/$f"
        echo "deleted  $f"
    fi
done </tmp/deleted-files.txt
