#!/usr/bin/bash
# TODO:
# 1. Support for iday, but anything but "current" is rejected.


usage() {
	exampleDate=$(date +%Y-%m-%d);
	echo "Usage: $0 <universeday> [interpretationday]";
	echo "(universeday is required, interpretationday support coming soon)";
	echo;
	echo "Day format: YYYY-MM-DD";
	echo "EG: $0 $exampleDate";
	echo "EG: $0 current";
	exit 1;
}

validDay() {
	local input="${1:-}"
	local date=""
	local y m d

	# 1) Extract date in supported formats: YYYY-MM-DD or YYYYMMDD
	if [[ "$input" =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})$ ]]; then
		y="${BASH_REMATCH[1]}"; m="${BASH_REMATCH[2]}"; d="${BASH_REMATCH[3]}"
		date="${y}-${m}-${d}"
	elif [[ "$input" =~ ^([0-9]{4})([0-9]{2})([0-9]{2})$ ]]; then
		y="${BASH_REMATCH[1]}"; m="${BASH_REMATCH[2]}"; d="${BASH_REMATCH[3]}"
		date="${y}-${m}-${d}"
	else
		echo ""
		return 0
	fi

	# 2) Validate it's a real date (reject 2026-02-30, etc.)
	# GNU date is available on EL; this is the cleanest check.
	if ! date -u -d "$date" +"%F" >/dev/null 2>&1; then
		echo ""
		return 0
	fi

	# Normalize (in case date did something weird; also ensures zero padding)
	date="$(date -u -d "$date" +"%F" 2>/dev/null)" || { echo ""; return 0; }

	# 3) Web hit check (HEAD, follow redirects, fail on non-2xx/3xx)
	# Treat 200-399 as "exists", anything else as failure.
	local url="https://archive.retrogrid.io/observed/almalinux/current/$date/9";
	local http_code
	http_code="$(curl -sS -L -o /dev/null -I -w '%{http_code}' "$url" 2>/dev/null || echo 000)"

	if [[ "$http_code" =~ ^2|^3 ]]; then
		echo "$date"
	else
		echo "invalid"
	fi

}

if [ "$1" = "" ] ; then
	usage;
fi;

# Lock management coordinates with dnf plugin
lock="/run/retrogrid/retrogrid.dnf.lock";
mkdir -p "/run/retrogrid";
exec 9>"$lock"
# Exclusive lock or quit
if ! flock -xn 9; then
  echo "retrogrid-set-day: another RetroGrid/DNF operation is in progress (lock: $lock)" >&2
  exit 75  # EX_TEMPFAIL is reasonable
fi
# export the FD number for children processes
export RETROGRID_LOCK_FD=9


date=$(validDay "$1");
if [ "$1" = 'current' ] ; then
	echo "current" > /etc/yum/vars/universeday;
	/usr/bin/dnf -y clean all 2>&1 >/dev/null;
	exit 0;
elif [ "$date" = "invalid" ] ; then
	echo "Unsupported Universe Day".
	exit 1;
elif [ "$date" = "" ] ; then
	usage;
else
	echo "$date" > /etc/yum/vars/universeday;
fi;

# clear out the cache since it's now assuredly stale
# dnf plugin inherits FD 9
/usr/bin/dnf -y clean all 2>&1 >/dev/null;
