#!/bin/sh
# Copyright (C) 2024-2024 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS

if [ $# -ne 2 ]; then
    echo "Usage: $0 bacula-file conf"
    echo "INFO: Nothing updated"
    exit 1
fi

if ! which base64 2>/dev/null > /dev/null; then
    echo "ERROR: core-utils must be installed"
    echo "INFO: Nothing updated"
    exit 3
fi

BIN=/opt/bacula/bin
ETC=/opt/bacula/etc
SYSTEMCTL=`which systemctl`

PRG=
if [ "$1" = "$ETC/bacula-fd.conf" ]; then
    PRG=bacula-fd

elif [ "$1" = "$ETC/bacula-sd.conf" ]; then
    PRG=bacula-sd

elif [ "$1" = "$ETC/bacula-dir.conf" ]; then
    PRG=bacula-dir

elif [ "$1" = "$ETC/bconsole.conf" ]; then
    PRG=bconsole

else
    echo "Usage $0 bacula-file conf"
    echo "INFO: Nothing updated"
    exit 2
fi

d=`date +%Y%m%d%H%M`
echo $2 | base64 --decode > "$1.$d.tmp"

if [ $? != 0 ]; then
    echo "ERROR: Unable to decode string"
    echo "INFO: Nothing updated"
    exit 4
fi

$BIN/$PRG -c "$1.$d.tmp" -t
if [ $? != 0 ]; then
    echo "ERROR: Unable to validate the configuration"
    echo "INFO: Nothing updated"
    rm -f $1.$d.tmp
    exit 5
fi

# create a backup of the original file
if [ -f "$1" ]; then
    echo "INFO: Creating a backup of the original configuration as $1.$d"
    cp -f "$1" "$1".$d
fi

echo "INFO: Creating new configuration file"
# Keep the same attributes
cat "$1.$d.tmp" >  "$1"
ret=$?

if [ $? = 0 ]; then
    echo "INFO: Configuration updated"
    if [ "$PRG" != "bconsole" ]; then
        echo "INFO: Restarting service $PRG"
        $SYSTEMCTL restart $PRG
        echo "INFO: Restarted service $PRG"
    fi
else
    echo "ERROR: Unable to update the configuration file"
    if [ -f "$1.$d" ]; then
        echo "INFO: Reverting to the original configuration"
        cp -f "$1.$d" "$1"
    fi
fi

rm -f $1.$d.tmp

exit $ret
