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

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

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

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

## 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

SharePath="${SharePath}/@tmp"
/bin/mkdir -p ${SharePath}
SwapFile=${SharePath}/swapfile

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
		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
		log_msg err "dd $SwapFile start."
		/bin/dd if=/dev/zero of="${SwapFile}" bs=${DD_BASE}M count=$(($SwapM / $DD_BASE))

		if [ $? -ne 0 ]; then
			_exit "dd swap failed !"
			exit 1
		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

	/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
