#!/bin/sh
# Copyright (c) 2000-2011 Synology Inc. All rights reserved.

HDPARM=/usr/syno/bin/hdparm
MAXPRINTER=`/bin/get_key_value /etc.defaults/synoinfo.conf maxprinters`
# Max Swap size = 4096 MB
MAXSWAP=4096
# Min Swap size = 10 MB
MINSWAP=10
# base on 10M to dd
DD_BASE=1
# use 1/4 available space as swap
QUOTA=4
SWAP_MKFLAG="/tmp/.makingswap"

log_msg()
{
	/usr/bin/logger -p $1 -t swapaction "$2"
}

_exit()
{
	log_msg err "$1"
	rm -f $SWAP_MKFLAG
}

ShareCnt=`synoshare --enum USB|grep Listed|awk '{print $1}'`
if [ "x$ShareCnt" != "x" ] && [ $ShareCnt -ge 2 ]; then
	local pgSqlPath=`/usr/syno/bin/servicetool --get-service-bin pgsql|awk -F"/" '{print "/" $2 "/" $3}'`
	local BIFS=$IFS;
	IFS=$'\n';

	for i in `/usr/syno/sbin/synoshare --enum USB| awk 'NR>2{print}'`; do
		local SelectPath=`/usr/syno/sbin/synoshare --get "$i"|grep Path|awk -F'[][]' '{print $2}'`
		if [ "x$pgSqlPath" != "x$SelectPath" ]; then
			SharePath="${SelectPath}/@sharebin"
			break;
		fi
	done
	IFS=$BIFS;
else
	## use pgsql volume first, then try first available volume
	SharePath=`/usr/syno/bin/servicetool --get-service-bin pgsql`
	if [ "$?" == "0" ]; then
		SharePath=`/usr/syno/bin/servicetool --get-first-alive-volume`
		if [ "$?" == "0" ]; then
			log_msg err "No available user space could be used for swap !"
			exit 1
		fi
		SharePath="${SharePath}/@sharebin"
	fi
fi

SharePath="${SharePath}/@tmp"
/bin/mkdir -p ${SharePath}
SwapFile=${SharePath}/swapfile
SYNODSMNOTIFY=/usr/syno/bin/synodsmnotify

MkSwap()
{
	if [ -e $SWAP_MKFLAG ]; then
		echo "swapaction is running. Won't create it again."
		exit 0
	fi
	if grep swapfile /proc/swaps >/dev/null; then
		# swap already on
		echo "Already turned on swapfile. Won't create it again."
		cat /proc/swaps
		/bin/chmod 600 "${SwapFile}" # always ensure correct swap permission
		exit 0
	fi
	BlSkipCreate=0
	SwapM=$(( `/bin/df -m $SharePath| /usr/bin/tail -n1| /usr/bin/awk '{print $4}'` / $QUOTA ))
	if [ $SwapM -gt $MAXSWAP ]; then
		SwapM=$MAXSWAP
	fi
	if [ $SwapM -lt $MINSWAP ]; then
		log_msg err "Skip to create swap. Only $SwapM MB left on disk."
		return;
	fi
	if [ -f "${SwapFile}" ]; then
		SwapFileM=`/usr/bin/du -m "${SwapFile}" | /usr/bin/cut -f 1`
		if [ $(( $SwapFileM / $DD_BASE )) -ge $(( $SwapM / $DD_BASE )) ]; then
			BlSkipCreate=1
		fi
	fi
	touch $SWAP_MKFLAG
	if [ "${BlSkipCreate}" -ne 1 ]; then
		/sbin/swapoff "${SwapFile}" 2>/dev/null
		if [ -x "${HDPARM}" ]; then # use fallocate for fast allocation
			log_msg err "fallocate $SwapFile start."
			rm -f $SwapFile
			${HDPARM} --fallocate "$(( $SwapM * 1024 ))" $SwapFile # hdparm --fallocate <KBytes> <file>
		fi

		# fallback for platforms & partitions (e.g., vfat) that do not support fallocate
		if [ ! -e "${SwapFile}" ]; then
			log_msg err "dd $SwapFile start."
			${SYNODSMNOTIFY} @administrators dsmnotify:system_event router_tips:legacy_swap_start
			/bin/dd if=/dev/zero of="${SwapFile}" bs=${DD_BASE}M count=$(( $SwapM / $DD_BASE ))

			if [ $? -ne 0 ]; then
				${SYNODSMNOTIFY} @administrators dsmnotify:system_event router_tips:legacy_swap_failed
				_exit "dd swap failed !"
				exit 1
			fi
			${SYNODSMNOTIFY} @administrators dsmnotify:system_event router_tips:legacy_swap_finish
		fi
		log_msg err "Use $(( $SwapM / $DD_BASE * $DD_BASE)) MB as swap"
	else
		log_msg err "Use $(( $SwapFileM / $DD_BASE * $DD_BASE)) MB as swap"
	fi

	/bin/chmod 600 "${SwapFile}"
	/sbin/mkswap "${SwapFile}"
	if [ $? -ne 0 ]; then
		_exit "mkswap failed !"
		exit 1
	fi

	/sbin/swapon "${SwapFile}" || log_msg err "swapon failed !"
}

case "$1" in
"on")
	MkSwap
	MemTotal=`cat /proc/meminfo | grep "MemTotal:" | awk '{print $2;}' `
	SwapTotal=`cat /proc/meminfo | grep "SwapTotal:" | awk '{print $2;}' `
	MaxMemLimit=$(( ($MemTotal + $SwapTotal) / 2 ))
	ulimit -v $MaxMemLimit
	_exit "Finish swap on action"
	
	exit 0
	;;
"off")
	/sbin/swapoff "$SwapFile"
	log_msg err "swapoff $SwapFile"

	exit 0
	;;
*)
	echo "Usage: $0 on/off"
	;;
esac
