#!/bin/bash
#custom hibernate script to avoid having to use a swap file

export DISPLAY=:0 

if mkdir /run/suspend_lock; then
	true #noop; continue below
else
	sudo -HE -u felix xmessage -center "suspend/hibernate already in progress"
	exit 1
fi

#tell Pidgin to go offline
sudo -HE -u felix /usr/bin/purple-remote "setstatus?status=offline"

#sync homedir
tmpsync
sync
#unmount /data and shut down crypt device (completely release SD card)
umount /data
cryptsetup luksClose data

if [ -d /data/_snapshots ]; then
	sudo -HE -u felix xmessage "hibernate aborted; couldn't unmount SD card (/data)"
	rmdir /run/suspend_lock
	exit
fi

swapon /dev/mmcblk0p2
#go to full speed for compression/encryption of hibernation image
cpufreq-set -r -f 1600MHz
sync
s2disk
swapoff -a
#kick the SD card controller in the ass to wake it up again:
#(workaround for "mmc0: Controller never released inhibit bit(s).")
#rmmod sdhci_pci
#rmmod sdhci
#modprobe sdhci_pci
. /etc/acpi/resumey-stuff.sh
alsactl restore
rmdir /run/suspend_lock
