#!/bin/bash
# Trigger a ZFS pool scrub.
# Usage: omv-zfs-scrub-job <pool> [-e always|onerror] [-c comment]
set -euo pipefail

LOGFILE="/var/log/omv-zfs-scrub.log"

POOL="$1"
shift || true

# Parse optional flags
email_mode=""
email_comment=""
while [[ $# -gt 0 ]]; do
    case "$1" in
        -e) email_mode="$2";    shift 2 ;;
        -c) email_comment="$2"; shift 2 ;;
        *)  shift ;;
    esac
done

# Output capture + email on exit
tmpfile=""
if [ -n "${email_mode}" ]; then
    tmpfile=$(mktemp)
    exec > "${tmpfile}" 2>&1
else
    exec > >(tee -a "${LOGFILE}") 2>&1
fi

_send_email() {
    local rc="$1"
    if [ -f "${tmpfile:-}" ]; then
        cat "${tmpfile}" >> "${LOGFILE}"
    fi
    if [ -n "${email_mode}" ] && [ -f "${tmpfile:-}" ]; then
        if [ "${email_mode}" = "always" ] || \
           { [ "${email_mode}" = "onerror" ] && [ "${rc}" -ne 0 ]; }; then
            mail -E -s "ZFS Scrub${email_comment:+ - ${email_comment}}" \
                 -a "From: Cron Daemon <root>" root < "${tmpfile}" >/dev/null 2>&1
        fi
        rm -f "${tmpfile}"
    fi
}
trap '_send_email $?' EXIT

if [ "${POOL}" = "*" ]; then
    pools=$(zpool list -H -o name,health 2>/dev/null | awk -F'\t' '$2=="ONLINE"{print $1}')
    if [ -z "${pools}" ]; then
        echo "$(date -Iseconds): No ONLINE pools found to scrub."
        exit 0
    fi
    echo "${pools}" | while read -r pool; do
        echo "$(date -Iseconds): Starting scrub on pool ${pool}"
        zpool scrub "${pool}"
        echo "$(date -Iseconds): Scrub started on pool ${pool}. Use 'zpool status ${pool}' to monitor progress."
    done
else
    echo "$(date -Iseconds): Starting scrub on pool ${POOL}"
    zpool scrub "${POOL}"
    echo "$(date -Iseconds): Scrub started on pool ${POOL}. Use 'zpool status ${POOL}' to monitor progress."
fi
