#!/bin/bash

if [ "$(id -u)" != "0" ]; then
  echo "This script must be run as root" 2>&1
  exit 1
fi

if [ "$#" -ne 2 ]; then
    echo "Usage: /usr/local/bin/create-swap.sh <swap_path> <swap_size>"
    exit 1
fi

SWAP_PATH=$1
SWAP_SIZE=$2
SWAP_EXISTS=`swapon -s | grep $SWAP_PATH`

if [ -z "$SWAP_EXISTS" ]; then
  dd if=/dev/zero of=$SWAP_PATH count=$SWAP_SIZE bs=1MiB
  chmod 600 $SWAP_PATH
  mkswap $SWAP_PATH
  swapon $SWAP_PATH
  printf "$SWAP_PATH\tswap\tswap\tsw\t0\t0\n" >> /etc/fstab
  echo "Swap disk created on path $SWAP_PATH with size $SWAP_SIZE"
else
  echo "Swap disk on path $SWAP_PATH already exists, skipping."
fi
