#!/bin/bash

source $HOME/.secrets/Backup/env.sh

for _ in {1..2}; do
    OUTPUT=$(echo "$ZFS_PASSPHRASE" | ssh 10.4.0.1 zfs load-key Vault/Thomas/Encrypted  2>&1);
    if [ "$OUTPUT" == "Key load error: Key already loaded for 'Vault/Thomas/Encrypted'." ]; then
        echo "Key successfully loaded, starting syncoid"
        syncoid --no-privilege-elevation --no-sync-snap tank/Storage/Thomas/Workspace 10.4.0.1:Vault/Thomas/Encrypted/Storage/Workspace
        syncoid --no-privilege-elevation --no-sync-snap tank/Storage/Thomas 10.4.0.1:Vault/Thomas/Encrypted/Storage/T
        syncoid --no-privilege-elevation --no-sync-snap tank/Storage/Niels 10.4.0.1:Vault/Thomas/Encrypted/Storage/N
        syncoid --no-privilege-elevation --no-sync-snap tank/Storage/Yolande 10.4.0.1:Vault/Thomas/Encrypted/Storage/Y
        syncoid --no-privilege-elevation --no-sync-snap tank/Containers 10.4.0.1:Vault/Thomas/Encrypted/Containers
        ssh 10.4.0.1 zfs unload-key Vault/Thomas/Encrypted
        exit 0
    fi
done

echo "Found output instead: $OUTPUT"
echo "Failed to load key: $OUTPUT" | sendmail
exit 1
