#!/bin/bash
#
# recordum_serial_fix
#
# v0.1 2014-02-18 RE
# v0.2 2014-02-24 loop the database connect to allow it to become available again - RE
#
# when we have a file with the serial number that differs from the database value, then write it into the database upon start up
# by adding the call to /etc/rc.local

SERIAL_FILE=/usr/local/recordum/SERIAL_CODE
SAVED_FILE=/backup/db_initial/900.restore.saved.global_config.sql
PSQLBIN=/usr/bin/psql

if [[ -f ${SERIAL_FILE} ]]
then
    # loop for five minutes
    MAX=15
    COUNT=0
    while (( COUNT < MAX ))
    do
        SERNUM=$( ${PSQLBIN} -Upostgres --set ON_ERROR_STOP=on -c"SELECT str_val FROM global_config WHERE id = 143" -A -t recordum )
        if [[ "$SERNUM" != "" ]]
        then
            break
        fi
        let COUNT++
        # 20 seconds
        sleep 20
    done
    # if we reached the end of the loop exit with a failure
    [[ ${COUNT} == ${MAX} ]] && exit 1

    SERNUM=$( ${PSQLBIN} -Upostgres -c"SELECT str_val FROM global_config WHERE id = 143" -A -t recordum )
    SERIAL=$( cat ${SERIAL_FILE} ) || exit 2
    if [[ "$SERIAL" != "" && "$SERIAL" != "$SERNUM" ]]
    then
        SERIAL_LC=$( echo ${SERIAL} | tr [A-Z] [a-z] )
        COUNT=$( ls -a /etc/openvpn/keys/* |grep "$SERIAL_LC" |wc -l )
        if [[ "$COUNT" -ge 2 ]]
        then
            ${PSQLBIN} -Upostgres -c"UPDATE global_config SET str_val = '$SERIAL' WHERE id=143;" -A -t recordum 2>&1 1>/dev/null
            if [[ -f ${SAVED_FILE} ]]
            then
                su - postgres -c "psql -d recordum < "${SAVED_FILE}
            fi
        fi
    fi
fi

exit 0
