#!/usr/bin/env bash
# All the zfs packages in debian stretch
apt install -y dkms busybox-static
apt install -y initramfs-tools dh-autoreconf
apt install -y linux-headers-$(uname -r) zfs-dkms zfs-initramfs zfsutils-linux
apt install -y zfs-zed

echo "linux default, mount partitions even if non-empty, the no option really only makes sense if the directory being mounted on has been declared as a mount point only and is therefore guaranteed to be empty."
sed -i "s,^\(DO_OVERLAY_MOUNTS=\).*,\1\'yes\'," /etc/default/zfs

echo "replace the pool name detection with zdb command in /etc/grub.d/10_linux."
sed -i "s|rpool=.*|rpool=\`zdb -l \${GRUB_DEVICE} \| grep -E '[[:blank:]]name' \| cut -d\\\' -f 2\`|"  /etc/grub.d/10_linux

echo "adding zfs scrub to cron.weekly"
cat > /etc/cron.weekly/zfs-scrub-weekly <<EOF
#!/bin/bash

# set PATH
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# set pool name
ZFS_POOL="rpool"

# start scrub
zpool scrub "$ZFS_POOL"
EOF

chmod +x /etc/cron.weekly/zfs-scrub-weekly

# Allow readonly zfs to non-root users in sudoers (put in place by zfsutils-linux)
cat <<-EOF | sudo tee -a /etc/sudoers.d/zfs
	# Allow read-only ZoL commands to be called through sudo
	# without a password. Remove the first '#' column to enable.
	#
	# CAUTION: Any syntax error introduced here will break sudo.
	#
	# Cmnd alias specification
	Cmnd_Alias C_ZFS = \
	  /sbin/zfs "", /sbin/zfs help *, \
	  /sbin/zfs get, /sbin/zfs get *, \
	  /sbin/zfs list, /sbin/zfs list *, \
	  /sbin/zpool "", /sbin/zpool help *, \
	  /sbin/zpool iostat, /sbin/zpool iostat *, \
	  /sbin/zpool list, /sbin/zpool list *, \
	  /sbin/zpool status, /sbin/zpool status *, \
	  /sbin/zpool upgrade, /sbin/zpool upgrade -v
	
	# allow any user to use basic read-only ZFS commands
	ALL ALL = (root) NOPASSWD: C_ZFS
EOF

modprobe zfs
