#!/bin/sh

# copyright 2006 Vagrant Cascadian <vagrant@freegeek.org>, distributed under
# the terms of the GNU General Public License version 2 or any later version.

# generates a swap file and configures nbd-server to export it
# to stdout. should usually be run from an inetd.

# default swapfile size (in MB)
SIZE=32

# default to running mkswap 
RUN_MKSWAP=true

if [ -f /etc/ltsp/nbdswapd.conf ]; then
    . /etc/ltsp/nbdswapd.conf
fi

if [ -n "$SWAPDIR" ]; then
    if [ -d "$SWAPDIR" ] && [ -w "$SWAPDIR" ]; then
        TEMPFILE_OPTS="${SWAPDIR}XXXXXX"
    else
        echo "ERROR: not a directory or not writeable: $SWAPDIR" > /dev/stderr
        exit 1
    fi
fi

if [ -z "$SWAP" ]; then
    SWAP=$(mktemp $TEMPFILE_OPTS)
fi

# generate the swap file
dd if=/dev/zero of=$SWAP bs=1024k count=$SIZE 2> /dev/null

if [ "$RUN_MKSWAP" = "true" ]; then
    /sbin/mkswap $SWAP > /dev/null 2>&1
fi

# start the swap server
/bin/nbd-server 0 $SWAP $NBD_SERVER_OPTS -C /dev/null > /dev/null 2>&1

# clean up the swap file
rm -f $SWAP
