#!/usr/bin/env bash

# Set umask to avoid problems on files created by the script
umask 0022

source /var/lib/shinken/libexec/libs/shinken_protected_fields.sh
source ../libs/shinken_protected_fields.sh 2>/dev/null   # For PyCharm


function usage()
{
    printf "\nUsage: $(basename $0) [backup directory]\n\n"
    printf "This command allows you to recover a key from a backup if its export was lost."
    printf "The result of this command must then be sent to your Shinken support to recover your key.\n"
    printf "\nOptions :\n"
    printf "  -h          : Shows this help text\n"
    printf "\nExample :\n"
    printf "\n$(basename $0) shinken-backups/2018-03-14__16-25-15\n\n"
    exit 1
}

if [ "$1" = "-h" ] || [ "$1" = "--help" ] || [ "$1" = "-help" ] ; then
    usage
fi

if [ $# -eq 1 ]; then
    backup_dir=$( readlink -f "$1")
else
    usage
fi


current_dir=$(pwd)
tmp_dir=$(mktemp -d)
pushd $tmp_dir >/dev/null
tar xfz ${backup_dir}/configuration/shinken-etc.tar.gz etc/shinken/synchronizer.cfg

keyfile=$(spf_get_keyfile_name_from_synchronizer_cfg_with_file etc/shinken/synchronizer.cfg)
if [ $? -ne 0 ]; then
    spf_show_error "Unable to find the key file name in the synchronizer configuration file from the backup"
    printf "Please make sure that this is a backup for Shinken Enterprise 2.5.0 or later\n\n"
    exit 1
fi
keyfile=$(basename "$keyfile")

keyfile_enc="etc/shinken/${keyfile#/}.enc"

tar  xfz ${backup_dir}/configuration/shinken-etc.tar.gz ${keyfile_enc}
popd >/dev/null
if [ ! -f "${tmp_dir}/$keyfile_enc" ]; then
    printf "\nYour backup does not contain the data necessary to recover your key\n"
    printf "Please make sure that this is a backup for Shinken Enterprise 2.5.0 or later\n\n"
    exit 1
fi

cp "${tmp_dir}/$keyfile_enc" "$current_dir"
rm -rf "${tmp_dir}"

printf "\nPlease send the file $(show_data $(basename "${keyfile_enc}")) that you can find in this directory to your Shinken support.\n"
printf "They will send you a restored key export.\n\n"
printf "You can use the command $(show_command shinken-protected-fields-keyfile-restore "") with that key export and restart your synchronizer\n\n"
printf "$(show_important_info "Note that this key will only apply to the database contained in the backup you specified (or other backups of the same database if the key was not changed)")\n\n"

exit 0
