#! /bin/sh

# swap-back v1.0
# Transfer swap content back into RAM
# Copyright (c) 2016 Raphaël Halimi <raphael.halimi@gmail.com>

# Source shell-script-helper
. /lib/shell-script-helper


#
# Variables
#

# Configuration files
SYSTEM_CONFIG_FILE="/etc/$(basename "$0").conf"
USER_CONFIG_FILE="$HOME/.$(basename "$0").conf"

# Options defaults
#VERBOSE=0
#DEBUG=0

#
# Functions
#

print_usage () {
  printf "Usage: %s [OPTION]...\n" "$(basename "$0")"
  printf "Transfer swap content back into RAM\n"
  printf "\nOPTIONS:\n"
  print_option "-v" "Verbose mode"
  print_option "-d" "Debug mode"
  print_option "-h" "Print this help message"
}


#
# Config files
#

[ -e "$SYSTEM_CONFIG_FILE" ] && . "$SYSTEM_CONFIG_FILE"
[ -e "$USER_CONFIG_FILE" ] && . "$USER_CONFIG_FILE"


#
# Options processing
#

while getopts "vdh" OPTION ; do
  case $OPTION in
    v) enable_verbose ;;
    d) enable_debug ;;
    h) print_usage ; exit 0 ;;
    *) print_usage ; exit 1 ;;
  esac
done ; shift $((OPTIND-1))


#
# Checks
#

root_only
lock_script


#
# MAIN
#

FREE_OUTPUT=$(free -b)
USED_SWP=$(printf "%s" "$FREE_OUTPUT" | grep "^Swap:" | awk '{print $3}')
FREE_MEM=$(printf "%s" "$FREE_OUTPUT" | grep "^Mem:" | awk '{print $7}')
print_debug "USED_SWP=$USED_SWP" "FREE_MEM=$FREE_MEM"

if [ "$FREE_MEM" -ge "$USED_SWP" ] ; then
  printf "Emptying swap..."
  /sbin/swapoff -a
  /sbin/swapon -a
  printf "done.\n"
else
  die "Not enough free memory to contain swap, aborting."
fi
