#!/bin/bash
#
# recordum_restore
#
# v0.1 2012-07-09 RE
# v0.2 2016-09-26 RE
# v0.3 2024-02-21 BEH Security Updates
#
# script to restore the configuration of the recordum database
# and various configuration files

MYSELF=$( basename $0 )

# backup directory and file list for the tar ball
BAKDIR=backup
DEFDIR=db_initial
BAKTEMPLATE=template/100.config.file.list

# helper
script_help() {
    cat <<EOF
${MYSELF} help:

This script restores a backup to your system.

Usage: ${MYSELF} -f BACKUP -p TEMPPATH \\
               [ -C CMD ]

where:
    BACKUP .... absolut path to a selected backup
    TEMPPATH .. were was the backup unpacked to?
    CMD ....... commands: drop, ..

EOF
}

if [[ $# -lt 2 ]]
then
    script_help
    exit 1
fi

while getopts "f:p:C:" option
do
    case ${option} in
    f)  BACKUP=$OPTARG
        ;;
    p)  TMPDIR=$OPTARG
        ;;
    C)  CMD=$OPTARG
        ;;
    *)  script_help
        exit 2
        ;;
    esac
done

# stop services that use the database
echo "Stopping all database using services"
sudo service recordum stop

echo "Starting LinSens in system repair mode for Hardware Watchdog"
sudo tee /tmp/sysstatus >/dev/null <<<"restore"
sudo service linsens start

# store current settings that should stay unchanged by a restore
# changed settings are recognised by a changed serial number upon startup
PSQLBIN=/usr/bin/psql
STATIONNAME=$( ${PSQLBIN} -Upostgres -c"SELECT str_val FROM global_config WHERE id = 142;" -A -t recordum )
MANUFACTUREDATE=$( ${PSQLBIN} -Upostgres -c"SELECT str_val FROM global_config WHERE id = 145;" -A -t recordum )
MODEMUSB=$( ${PSQLBIN} -Upostgres -c"SELECT str_val FROM global_config WHERE id = 1827;" -A -t recordum )
NTPCHECK=$( ${PSQLBIN} -Upostgres -c"SELECT str_val FROM global_config WHERE id = 1877;" -A -t recordum )
cat > /backup/db_initial/900.restore.saved.global_config.sql <<EOF
SELECT cp_updateelems('global_config', 'id',
 '{142,145,995,1388,1389,1390,1827,1877}'::int[],
 '{
    "UPDATE global_config SET str_val = ''${STATIONNAME}'' WHERE id = 142;",
    "UPDATE global_config SET str_val = ''${MANUFACTUREDATE}'' WHERE id = 145;",
    "UPDATE global_config SET str_val = ''0'', int_val = 0 WHERE id = 995;",
    "UPDATE global_config SET str_val = ''1'', int_val = 1 WHERE id = 1388;",
    "UPDATE global_config SET str_val = ''1'', int_val = 1 WHERE id = 1389;",
    "UPDATE global_config SET str_val = ''1'', int_val = 1 WHERE id = 1390;",
    "UPDATE global_config SET str_val = ''${MODEMUSB}'', int_val = ${MODEMUSB} WHERE id = 1827;",
    "UPDATE global_config SET str_val = ''${NTPCHECK}'', int_val = ${NTPCHECK} WHERE id = 1877;"
  }'
) AS global_config;
EOF

# drop measurement data
if [[ -n "$CMD" ]] && [[ "$CMD" == "drop" ]]
then
    /usr/local/recordum/dataproc/removedatatables -a
fi
if [[ -n "$CMD" ]] && [[ "$CMD" == "reset" ]]
then
    /usr/local/recordum/dataproc/removedatatables -a
fi
# drop db
#echo "Dropping the database"
#su - postgres -c "dropdb recordum"
# and restore the backup
#echo "Starting the restore"
#su - postgres -c "pg_restore --create --verbose -d postgres "$BACKUP
su - postgres -c "pg_restore --clean --verbose -d recordum "${BACKUP}
# now fire all db updates currently installed on the machine
echo "Re-running the installed database update scripts"
FILE_LIST=$( ls /${BAKDIR}/${DEFDIR}/3*patches*sql 2>/dev/null )
for file in ${FILE_LIST}; do
    echo ${file}
    su - postgres -c "psql -d recordum < "${file}
done

# empty tables
if [[ -n "$CMD" ]] && [[ "$CMD" == "drop" ]]
then
    # test for the type of the backup: all (full) or cfg (only); awk will fail with path names containing dots
    TYPE=$( echo ${BACKUP} | awk '{n = split($0,a,"."); print a[2]}' )
    if [[ "$TYPE" != "all" ]]
    then
        echo "Empty tables"
        ${PSQLBIN} -Upostgres -c"DELETE FROM status_actual;" -A -t recordum
        ${PSQLBIN} -Upostgres -c"DELETE FROM status_history;" -A -t recordum
        ${PSQLBIN} -Upostgres -c"DELETE FROM aqa_jobs;" -A -t recordum
    fi
fi
# empty tables and overwrite system files
if [[ -n "$CMD" ]] && [[ "$CMD" == "reset" ]]
then
    # test for the type of the backup: all (full) or cfg (only); awk will fail with path names containing dots
    TYPE=$( echo ${BACKUP} | awk '{n = split($0,a,"."); print a[2]}' )
    if [[ "$TYPE" != "all" ]]
    then
        echo "Empty tables"
        ${PSQLBIN} -Upostgres -c"DELETE FROM sensors;" -A -t recordum
        ${PSQLBIN} -Upostgres -c"DELETE FROM sensors_idmap;" -A -t recordum
        ${PSQLBIN} -Upostgres -c"DELETE FROM status_actual;" -A -t recordum
        ${PSQLBIN} -Upostgres -c"DELETE FROM status_history;" -A -t recordum
        ${PSQLBIN} -Upostgres -c"DELETE FROM aqa_jobs;" -A -t recordum
    fi
    sudo cp -v $TMPDIR/etc/ddclient.conf /etc/.
    sudo chown -v root:root /etc/ddclient.conf
    sudo cp -v $TMPDIR/etc/hosts /etc/.
    sudo chown -v root:root /etc/hosts
    sudo cp -v $TMPDIR/etc/wvdial.conf /etc/.
    sudo chown -v root:dialout /etc/wvdial.conf
    sudo cp -v $TMPDIR/etc/network/interfaces  /etc/network/.
    sudo chown -v recordum:staff /etc/network/interfaces
    sudo cp -v $TMPDIR/usr/local/recordum/conf/watchdog.config /usr/local/recordum/conf/.
    sudo chown -v root:root /usr/local/recordum/conf/watchdog.config
fi
# rebuild statistics
echo "Rebuild statistics"
${PSQLBIN} -Upostgres -c"ANALYZE VERBOSE;" -A -t recordum

# init new global_config defaults
GC_UPDATE=/usr/local/recordum/dataproc/globalconfigmaintenance
if [[ -f ${GC_UPDATE} ]]
then
    ${GC_UPDATE}
fi

# system is ready again
sudo service linsens stop
sudo tee /tmp/sysstatus >/dev/null <<<"ready"

# here add script restore later; for now we try to avoid strange interactions

# reboot
if [[ -f /var/local/recordum/watchdog_queue ]]
then
    echo "Telling watchdog to reboot"
    sudo tee -a /var/local/recordum/watchdog_queue >/dev/null <<<"reboot"
    sudo service watchdog start
else
    echo "Doing the reboot by hand"
    sudo reboot
fi

# full success
exit 0
