#!/usr/local/bin/bash

#
# signer sync script authorized_keys wrapper
# to be used in authorized_keys as the explicit command allowed for a given key
#

# 
# NOTICE:
# when we're wrapping rsync in an authorized_keys command, we cannot output anything
# to stdout; otherwise rsync will fail
#

# there should never be more than one instance of this running
if pgrep -f "/usr/local/bin/bash $0" >/dev/null; then
    date >> "/var/log/sync_keys_wrapper_errors.log"
    echo "SSH connection: $SSH_CLIENT" >> "/var/log/sync_keys_wrapper_errors.log"
    echo "ERROR: $0 already running" | tee -a "/var/log/sync_keys_wrapper_errors.log";
    echo >> "/var/log/sync_keys_wrapper_errors.log";
    exit 1;
fi


# let's make sure we have something to work with
# use $1 for the command, but *only* if SSH_ORIGINAL_COMMAND is not set at all
if [ -z ${SSH_ORIGINAL_COMMAND+x} ]; then
  SSH_ORIGINAL_COMMAND="$1"
fi

# handle supported commands
case "$SSH_ORIGINAL_COMMAND" in
    
    # handle zone-restore from backupdir
    "deploy-rsynced-backup")
        echo "    - [$HOSTNAME] knotc zone-restore from /var/tmp/knot-sync"
        knotc zone-restore +backupdir "/var/tmp/knot-sync" +nozonefile +nojournal +notimers +kaspdb +nocatalog
        exit $?
        ;;
        
    # rsync of the backupdir
    "rsync --server -vlogDtprce.iLsfxCIvu --delete . /var/tmp/knot-sync/")
        rsync --server -vlogDtprce.iLsfxCIvu --delete . "/var/tmp/knot-sync/";
        exit $?;
        ;;
    
    # anything else - log and complain
    *)
        date >> "/var/log/sync_keys_wrapper_errors.log"
        echo "SSH connection: $SSH_CLIENT" >> "/var/log/sync_keys_wrapper_errors.log"
        echo "ERROR: Unexpected/unsupported command:" | tee -a "/var/log/sync_keys_wrapper_errors.log";
        echo "ERROR: $SSH_ORIGINAL_COMMAND" | tee -a "/var/log/sync_keys_wrapper_errors.log";
        echo >> "/var/log/sync_keys_wrapper_errors.log";
        exit 2;
        ;;
esac
