#!/bin/bash
# Create an empty file in /mnt and activate it as a swap
# Author: Tomas M <http://www.slax.org>
#

# only root can run this
if [ "0$UID" -ne 0 ]; then
   echo "Only root can run $(basename $0)"; exit 1
fi

SWAPFILE=$(readlink -f "$1")
SWAPSIZE="$2"

if [ $(($SWAPSIZE)) -lt 1 ]; then
   echo >&2
   echo "mkfileswap - create swap as a file in writable filesystem" >&2
   echo "usage: $0 [/mnt/partition/new_name.swap] [size MB]" >&2
   echo >&2
   exit 1
fi

if [ -d "$SWAPFILE" ]; then
   echo "$SWAPFILE is a directory, use $SWAPFILE/slax.swp instead" >&2
   exit 2
fi

if [ "$(echo "$SWAPFILE" | egrep "^/mnt")" = "" ]; then
   echo "you must use path in /mnt, I am sorry" >&2
   exit 3
fi

echo "Creating empty file $SWAPFILE, size $SWAPSIZE MB"
dd if=/dev/zero of=$SWAPFILE count=$SWAPSIZE bs=1M 2>/dev/null
if [ "$?" -ne 0 ]; then exit 4; fi

echo "Formating the file with Linux Swap filesystem..."
mkswap $SWAPFILE >/dev/null
if [ "$?" -ne 0 ]; then exit 5; fi

echo "Activating swap..."
swapon $SWAPFILE
if [ "$?" -ne 0 ]; then exit 6; fi
