#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Run bashclub-zsync with removable disk

set -euo pipefail

if [ -f $1 ]; then
  source $1
else
  echo "Configuration file $1 not found."
  exit 1
fi

pool=$(echo $target | cut -d'/' -f1)
timestamp=$(date +"%Y-%m-%d-%H%M")

echo "Starting zsync-autorun for pool $pool"
echo "ZFS replication to removable disk $pool started at $timestamp" | mail -s "zsync-autorun - Starting replication to $pool" root@localhost

sleep 0.5

disk=$(/usr/sbin/blkid | grep $pool | cut -d':' -f1)
luks=0

if /usr/sbin/blkid | grep $pool | grep LUKS > /dev/null 2<&1; then
  luks=1
  echo "Decrypting LUKS volume"
  if [ ! -f /etc/bashclub/${pool}.key ]; then
    echo "No keyfile found at /etc/bashclub/${pool}.key - Exiting..."
    exit 1
  fi
  /usr/sbin/cryptsetup open $disk $pool --key-file /etc/bashclub/${pool}.key
fi

sleep 0.5

if /usr/sbin/zpool import | grep -m1 $pool > /dev/null 2>&1 ; then

  echo "Importing zpool $pool"
  /usr/sbin/zpool import -f $pool
  /usr/sbin/zpool wait $pool
else
  echo "No importable zfs pool found"
  exit 1
fi

guid=$(zpool get guid -H -o value $pool)

sleep 0.5

if /usr/bin/bashclub-zsync -d -c $1 > /var/log/bashclub-zsync/zsync-autorun_${pool}.log ; then
  subject="zsync-autorun - Replication succeeded for $pool"
  success="ZFS replication to removable disk $pool successful
Started: $timestamp
Finished: $(date +%Y-%m-%d-%H%M)"
else
  subject="zsync-autorun - Replication failed for $pool"
  success="ZFS replication to removable disk $pool failed
Started: $timestamp
Finished: $(date +%Y-%m-%d-%H%M)

Checkzfs output (warning or critical):
$(grep -E "^1.*(vm|subvol)" /var/lib/check_mk_agent/spool/${checkzfs_spool_maxage}_${checkzfs_prefix} || true)
"
fi

echo "Running zpool scrub"
dayofweek=$(date +%u)
if [[ $dayofweek -ge 5 ]]; then
        zpool scrub $pool
        zpool wait $pool
fi

echo "Syncing $pool"
zpool sync $pool

echo "Getting zpool status"
success="$success
Zpool status $pool:
$(zpool status $pool)"

echo "Exporting $pool"
zpool export $pool

if [ $luks -gt 0 ]; then
  echo "Closing crypt volume"
  /usr/sbin/cryptsetup close $pool
fi

echo "Ejecting disk"
# whole disk of the partition (also nvme0n1p1 -> nvme0n1), as before if lsblk does not know it
parent=$(lsblk -no PKNAME "$disk" 2> /dev/null | head -1 || true)
if [[ -n $parent ]]; then
  udisksctl power-off --block-device /dev/$parent || echo "Power-off failed, the pool is exported, the disk can be removed"
else
  udisksctl power-off --block-device ${disk::-1} || echo "Power-off failed, the pool is exported, the disk can be removed"
fi

echo "$success" | mail -s "$subject" root@localhost

echo "Finished"
