#!/bin/sh
# systemd-sleep hook: offline low-power CPUs before suspend; online them after resume.
# Installed location (on system): /usr/lib/systemd/system-sleep/suspend-ops

CPU_LIST_FILE="/sys/devices/cpu_lowpower/cpus"
STATE_DIR="/run/suspend-ops"
STATE_FILE="$STATE_DIR/cpu_online_state"

log() {
	if command -v logger >/dev/null 2>&1; then
		logger -t suspend-ops -- "$*"
	else
		echo "suspend-ops: $*" >&2
	fi
}

# Expand a Linux cpulist format string, e.g. "0-3,8,10-12" -> one CPU id per line.
expand_cpulist() {
	list="$(printf '%s' "$1" | tr -d ' \t\r\n')"
	[ -z "$list" ] && return 0

	printf '%s\n' "$list" | tr ',' '\n' | while IFS= read -r part; do
		[ -z "$part" ] && continue
		case "$part" in
			*-*)
				seq $(printf '%s' "$part" | tr '-' ' ')
				;;
			*)
				echo "$part"
				;;
		esac
	done | sort -n -u
}

set_cpu_online_state() {
	cpu=$1
	state=$2
	online_file="/sys/devices/system/cpu/cpu${cpu}/online"

	[ -e "$online_file" ] || return 0
	echo "$state" >"$online_file" 2>/dev/null || return 1
}

cpulist_set_online() {
	cpulist=$1
	state=$2

	expand_cpulist "$cpulist" \
		| while IFS= read -r cpu; do
			[ -z "$cpu" ] && continue
			[ -d "/sys/devices/system/cpu/cpu$cpu" ] || continue
			if ! set_cpu_online_state "$cpu" "$state"; then
				log "Failed to set cpu$cpu online=$state"
			fi
		done
}

save_state_and_offline() {
	[ -r "$CPU_LIST_FILE" ] || return 0

	# Normalize to a single cpulist line; file is expected to already be valid.
	cpulist="$(tr -d ' \t\r\n' <"$CPU_LIST_FILE" 2>/dev/null)"
	[ -z "$cpulist" ] && return 0

	if ! mkdir -p "$STATE_DIR" 2>/dev/null; then
		log "Failed to create state dir: $STATE_DIR; skipping CPU offlining"
		return 0
	fi

	tmp_file="$STATE_FILE.$$.tmp"
	if ! printf '%s' "$cpulist" >"$tmp_file" 2>/dev/null; then
		rm -f "$tmp_file" 2>/dev/null || true
		log "Failed to write temp state file: $tmp_file; skipping CPU offlining"
		return 0
	fi

	if ! mv -f "$tmp_file" "$STATE_FILE" 2>/dev/null; then
		rm -f "$tmp_file" 2>/dev/null || true
		log "Failed to persist state file: $STATE_FILE; skipping CPU offlining"
		return 0
	fi

	cpulist_set_online "$cpulist" 0
}

restore_state() {
	[ -r "$STATE_FILE" ] || return 0

	cpulist="$(cat "$STATE_FILE" 2>/dev/null)"
	rm -f "$STATE_FILE" 2>/dev/null || true

	cpulist_set_online "$cpulist" 1
}

case "${1:-}" in
	pre)
		log "pre+"
		save_state_and_offline
		log "pre-"
		;;
	post)
		log "post+"
		restore_state
		log "post-"
		;;
	*)
		exit 0
		;;
esac

exit 0
