#!/usr/bin/env bash

ROOT_DATASET=$(zfs list -H -o name,mountpoint | awk '$2 == "/" { print $1 }')
if [ -z "$ROOT_DATASET" ]; then
  echo "Error: Could not detect ZFS dataset mounted at /" >&2
  exit 1
fi

# Usually the pool name is the first component (rpool/ROOT/ubuntu → rpool)
POOL_NAME="${ROOT_DATASET%%/*}"

#  Create zfs snapshots before apt operations using apt hooks

# 1. Create a Snapshot Script
# Create /usr/local/sbin/snapPrepApt
conf_print_snapPrepApt() {
  cat <<EOF
  #!/bin/bash
DATE="\$(date +%F-%T)"
zfs snapshot -r ${POOL_NAME}@snap_pre_apt_\$DATE
EOF
}
conf_print_snapPrepApt | sudo tee /usr/local/sbin/snapPrepApt
sudo chmod +x /usr/local/sbin/snapPrepApt

# 2. Add Apt Hook
# Create /etc/apt/apt.conf.d/90zfs-pre-apt-snapshot
conf_print_apt_conf_d() {
  cat <<EOF
DPkg::Pre-Invoke {"/usr/local/sbin/snapPrepApt || true";};   
EOF
}
conf_print_apt_conf_d | sudo tee /etc/apt/apt.conf.d/90zfs-pre-apt-snapshot

# 3. Kernel Updates
# Use /etc/kernel/preinst.d/ to snapshot before kernel installation:
conf_print_kernel_preinst_d() {
  cat <<EOF
#!/bin/bash
DATE="\$(date +%F-%T)"
zfs snapshot -r \${POOL_NAME}@pre-kernel_\${DATE}
EOF
}
conf_print_kernel_preinst_d | sudo tee /etc/kernel/preinst.d/90zfs-pre-kernel-snapshot
sudo chmod +x /etc/kernel/preinst.d/90zfs-pre-kernel-snapshot
