#!/bin/bash
#
# This utility creates the file which contains the VSS ID
# of the backup we just ingested. This is so we can keep
# track of the most recent VSS ID that we have performed
# a backup from.
#
#
# $1 = path to backup settings file containing VSS information
#      (currently we expect this to be a JSON file with the VSS
#      ids stored under a "new_guid" key).
#
# $2 = path to vss id file.
#
# $3 = Drive letter we are grabbing the VSS id for
#

SETTINGS_FILE=$1
VSS_FILE=$2
DRIVE=$3

# declare a number that will not be interpreted
# as one of the vdiff-backup error codes
declare -r EXIT_FAILURE=234

eprintf () {
    echo "$@" 1>&2
}

write_file () {
    FILE_PATH=${VSS_FILE%/*}
    [ -d "$FILE_PATH" ] || mkdir -p "$FILE_PATH"
    echo -e "$1" > "$VSS_FILE"
}

if [ ! -f $SETTINGS_FILE ]; then
    eprintf "Settings file not valid"
    exit $EXIT_FAILURE
fi

if [ -z $VSS_FILE ]; then
    eprintf "VSS file not valid"
    exit $EXIT_FAILURE
fi

if [ -z $DRIVE ]; then
    eprintf "No Drive Letter provided"
    exit $EXIT_FAILURE
fi

list_contents=$(sed -e '1,/new_guid/d' -e '/\}\,/,$d' "$SETTINGS_FILE" | grep \"$DRIVE\")

if [ $? -ne 0 ] || [ "$list_contents" == "" ]; then
    eprintf "Error parsing JSON settings file"
    write_file "VSS ID unknown"
    exit $EXIT_FAILURE
fi

vss_id=$(echo $list_contents | awk ' {split($0, arr, "[{}]"); print arr[2]}')

if [ $? -ne 0 ] || [ "$vss_id" == ""  ]; then
    eprintf "Could not read VSS ID from JSON settings file"
    write_file "VSS ID unknown"
    exit $EXIT_FAILURE
fi

write_file $vss_id
# Make file readable by non-root users
chmod 644 $VSS_FILE