#!/usr/bin/env bash
set -euo pipefail

CRONFILE="$HOME/.local/bin/mycronjobs.txt"

# -------- sanity check --------------------------------------------------------
if [[ ! -f "$CRONFILE" ]]; then
	echo "❌  $CRONFILE not found" >&2
	exit 1
fi

# -------- load current crontab (may be empty) -------------------------------
TMP_OLD=$(mktemp)
crontab -l 2>/dev/null >"$TMP_OLD" || true

# -------- read existing cron jobs into array ---------------------------------
existing_jobs=()
while IFS= read -r line; do
	# skip empty and comment lines
	[[ "$line" =~ ^[[:space:]]*$ ]] && continue
	[[ "$line" =~ ^[[:space:]]*# ]] && continue
	existing_jobs+=("$line")
done <"$TMP_OLD"

# -------- read new cron jobs into array --------------------------------------
new_jobs=()
while IFS= read -r line; do
	# skip empty and comment lines
	[[ "$line" =~ ^[[:space:]]*$ ]] && continue
	[[ "$line" =~ ^[[:space:]]*# ]] && continue
	new_jobs+=("$line")
done <"$CRONFILE"

# -------- merge jobs ---------------------------------------------------------
added=()
skipped=()

TMP_NEW=$(mktemp)
cp "$TMP_OLD" "$TMP_NEW" # start with existing jobs

for job in "${new_jobs[@]}"; do
	found=0
	for existing in "${existing_jobs[@]}"; do
		if [[ "$existing" == "$job" ]]; then
			found=1
			break
		fi
	done

	if ((found)); then
		skipped+=("$job")
	else
		echo "$job" >>"$TMP_NEW"
		added+=("$job")
	fi
done

# -------- install crontab if changed -----------------------------------------
if [ ${#added[@]} -eq 0 ]; then
	echo "ℹ️  No new cron jobs to add; all jobs already present."
else
	crontab "$TMP_NEW"
	echo "✅  Added ${#added[@]} new cron job(s):"
	for job in "${added[@]}"; do
		echo "   + $job"
	done
fi

# Report skipped jobs
if [ ${#skipped[@]} -gt 0 ]; then
	echo "ℹ️  Skipped ${#skipped[@]} existing job(s):"
	for job in "${skipped[@]}"; do
		echo "   - $job"
	done
fi

rm -f "$TMP_OLD" "$TMP_NEW"

# -------- ensure cron is running ---------------------------------------------
case "$(uname -s)" in
Linux)
	if command -v systemctl >/dev/null &&
		! systemctl --quiet is-active cron; then
		echo "ℹ️  Starting cron via systemctl…"
		sudo systemctl start cron
	fi
	;;
Darwin)
	echo "✅  macOS: cron will run automatically via launchd."
	;;
*)
	echo "⚠️  Unknown OS; ensure cron or launchd is active."
	;;
esac
