#!/bin/sh -eu

# Copyright (c) 2023, Evilham (https://evilham.com)
# BSD 2-Clause copyright and disclaimer apply.
# See: http://www.opensource.org/licenses/bsd-license.php

DS="$1"

DRY_RUN="${DRY_RUN:-YES}"

epoch_to_time() {
	epoch="$1"
	date -j -f '%s' "${epoch}" '+%Y-%m-%d_%H:%M:%S'
}

target_name() {
	snap_epoch="$1"
	snap_name="$2"
	snap_time="$(epoch_to_time "${snap_epoch}")"
	case "${snap_name}" in
		quarter_hourly-*)
			# quarter_hourly --> frequently
			printf "autosnap_%s_%s" "${snap_time}" "frequently"
		;;
		hourly-*)
			printf "autosnap_%s_%s" "${snap_time}" "hourly"
		;;
		daily-*)
			printf "autosnap_%s_%s" "${snap_time}" "daily"
		;;
		weekly-*)
			printf "autosnap_%s_%s" "${snap_time}" "weekly"
		;;
		monthly-*)
			printf "autosnap_%s_%s" "${snap_time}" "monthly"
		;;
		yearly-*)
			printf "autosnap_%s_%s" "${snap_time}" "yearly"
		;;
		*)
			# Empty --> no renaming
		;;
	esac
}


zfs list -rpHt snap -s creation -o creation,name "$DS" | while IFS='' read -r line; do
	snap_epoch="$(echo "${line}" | cut -f 1)"
	full_snap="$(echo "${line}" | cut -f 2)"
	ds_name="$(echo "${full_snap}" | cut -d '@' -f 1)"
	snap_name="$(echo "${full_snap}" | cut -d '@' -f 2-)"

	snap_target_name="$(target_name "${snap_epoch}" "${snap_name}")"

	if [ -n "${snap_target_name}" ]; then
		# We use DS to facilitate comparing local and remote actions
		printf "%s@%s\t-->\t%s@%s\n" "DS" "${snap_name}" "DS" "${snap_target_name}"
		if [ "${DRY_RUN}" != "YES" ]; then
			echo "zfs rename \"${full_snap}\" \"${ds_name}@${snap_target_name}\""
			zfs rename "${full_snap}" "${ds_name}@${snap_target_name}"
		fi
	fi
done
