#!/bin/sh
set -uo pipefail
set +e
exec 0<&-

#logfile="/mnt/SDCARD/.userdata/tg5040/logs/suspend_$(date +%Y%m%d_%H%M%S).log"
#exec >> "$logfile" 2>&1

wifid_running=
bluetoothd_running=

sleep_retval=

asound_state_dir=/tmp/asound-suspend

before() {
	>&2 echo "Preparing for suspend..."

	# Run pre-sleep hooks synchronously before services are stopped.
	# Subshell ensures a crashing hook cannot block suspend.
	( "$SYSTEM_PATH/bin/run_hooks.sh" pre-sleep.d --sync-only ) >/dev/null 2>&1 || true

	>&2 echo "Saving mixer state..."
	mkdir -p "$asound_state_dir"
	alsactl --file "$asound_state_dir/asound.state.pre" store || true

	if pgrep bluetoothd; then
		bluetoothd_running=1
		>&2 echo "Stopping bluetoothd..."
		$SYSTEM_PATH/etc/bluetooth/bt_init.sh stop || true
	fi

	if pgrep wpa_supplicant; then
		wifid_running=1
		>&2 echo "Stopping wpa_supplicant..."
		$SYSTEM_PATH/etc/wifi/wifi_init.sh stop || true
	fi
}

after() {
	>&2 echo "Resumed from suspend."

	# Run post-resume hooks in background immediately after wake.
	( "$SYSTEM_PATH/bin/run_hooks.sh" post-resume.d ) >/dev/null 2>&1 &

	if [ -n "$wifid_running" ]; then
		>&2 echo "Starting wpa_supplicant..."
		$SYSTEM_PATH/etc/wifi/wifi_init.sh start || true
	fi

	if [ -n "$bluetoothd_running" ]; then
		>&2 echo "Starting bluetoothd..."
		/etc/bluetooth/bt_init.sh start || true
	fi

	# >&2 echo "Restoring mixer state..."
	# alsactl --file "$asound_state_dir/asound.state.post" store || true
	# alsactl --file "$asound_state_dir/asound.state.pre" restore || true
}

before

>&2 echo "Suspending..."
sleep_max_tries=5
for i in $(seq 1 $sleep_max_tries); do
	>&2 echo "Deep sleep attempt $i of $sleep_max_tries"

	echo mem >/sys/power/state
	sleep_retval=$?

	>&2 echo "Deep sleep: kernel returned $sleep_retval"
	if [ $sleep_retval -eq 0 ]; then
	    break
	fi

	>&2 echo "Deep sleep failed: retrying in 3 seconds"
	sleep 3
done

# Resume services in background to reduce UI latency
after &

exit $sleep_retval
