#!/usr/bin/sh
set -eu

source_file=/var/lib/rgoon-sync/pending/repogoon-config.yml
target_directory=/etc/repogoon
target_file=${target_directory}/config.yml
temporary_file=${target_directory}/.config.yml.rgoon-sync-new
backup_directory=/var/lib/rgoon-sync/repogoon-config-backups
backup_file=${backup_directory}/config.yml.previous

if [ ! -f "$source_file" ] || [ -L "$source_file" ]; then
    echo "Pending RepoGoon configuration is missing or unsafe" >&2
    exit 1
fi

if [ ! -s "$source_file" ]; then
    echo "Pending RepoGoon configuration is empty" >&2
    exit 1
fi

install -d -o root -g repogoon -m 0750 "$target_directory"
install -d -o repogoon -g repogoon -m 0750 "$backup_directory"
had_previous=false
if [ -f "$target_file" ] && [ ! -L "$target_file" ]; then
    install -o repogoon -g repogoon -m 0600 "$target_file" "$backup_file"
    had_previous=true
fi
was_active=false
if systemctl is-active --quiet repogoon.service; then
    was_active=true
fi
rm -f -- "$temporary_file"
install -o root -g repogoon -m 0640 "$source_file" "$temporary_file"
mv -f -- "$temporary_file" "$target_file"

if command -v restorecon >/dev/null 2>&1; then
    restorecon -F "$target_file" >/dev/null 2>&1 || :
fi

if [ "$was_active" = true ] && ! systemctl restart repogoon.service; then
    if [ "$had_previous" = true ]; then
        install -o root -g repogoon -m 0640 "$backup_file" "$target_file"
    else
        rm -f -- "$target_file"
    fi
    systemctl start repogoon.service || :
    echo "RepoGoon rejected the synchronized configuration; previous config restored" >&2
    exit 1
fi

rm -f -- "$source_file"
