#!/bin/bash

restoreDir="/etc/restore"


hook_check() {
    if [[ -d "$restoreDir" ]]; then
        rm -rf "$restoreDir" || exit 1
    fi
}

hook_pre() {
    mkdir -p "$restoreDir" || exit 1
    pushd "$restoreDir" || exit 2

    dpkg --get-selections > Package.list
    aptitude search --disable-columns -F%p '~i!~M!~v' > InstallOnly.list
    #apt-key exportall > /etc/restore/Repo.keys
    rsync -avhHi /etc/apt/trusted.gpg.d /etc/restore/

    cat > restore.sh <<EOF
#!/bin/bash

if [[ ! -f "InstallOnly.list" ]]; then
    echo "This needs to be run inside the restore directory."
    exit 1
fi
if [[ ! -d "trusted.gpg.d" ]]; then
    echo "This needs to be run inside the restore directory."
    exit 1
fi

#apt-key add /etc/restore/Repo.keys
#dpkg --set-selections < /etc/restore/Package.list
#apt-get dselect-upgrade

install=""

dpkg-query -l 'rsync' &>/dev/null      || install+=" rsync"
dpkg-query -l 'aptitude' &>/dev/null   || install+=" aptitude"
dpkg-query -l 'borgbackup' &>/dev/null || install+=" borgbackup"
dpkg-query -l 'borgmatic' &>/dev/null  || install+=" borgmatic"

if [[ -n "\$install" ]]; then
    apt -y install \$install
fi

rsync --ignore-existing -raz trusted.gpg.d/ /etc/apt/trusted.gpg.d/
xargs aptitude --schedule-only install < InstallOnly.list
aptitude install
EOF

    popd || exit 2
}

hook_post() {
    rm -rf "$restoreDir"
}


case "$1" in
    before_check)   hook_check || exit $?;;
    before_backup)  hook_pre   || exit $?;;
    after_backup)   hook_post  || exit $?;;
esac