#!/usr/bin/env bash

# Usage:       ./clean-memory
#                or
#              bash clean-memory
# Description: Tries to free the memory (incl. swap)
# Author:      Patrick Neumann (patrick@neumannsland.de)
# Platform:    Raspbian GNU/Linux 9.x
# Version:     1.01
# Date:        2019-04-30 (first release: 2010-06-01)
# Link:        (work in progress)
# License:     GPL3
# Warranty:    This program is distributed WITHOUT ANY WARRANTY

#-------------------------------------------------------------------------------
# root-only
#-------------------------------------------------------------------------------
if [ $( id -u ) -ne 0 ] ; then
  echo "You have to be root!"
  exit 1
fi

#=== CONFIGURATION (user) ======================================================
DBG="off"

#-------------------------------------------------------------------------------
# This is the real magic of this script...
#-------------------------------------------------------------------------------
if [ "${DBG}" = "on" ] ; then
  ### before:
  echo "Before:"
  swapon -s
  free -m
  echo
fi

#-------------------------------------------------------------------------------
# empty cache (1/2)
#-------------------------------------------------------------------------------
echo 3 > /proc/sys/vm/drop_caches

#-------------------------------------------------------------------------------
# empty swap
#-------------------------------------------------------------------------------
if grep -E "^/dev/.*swap" /etc/fstab 2>&1 > /dev/null ; then
  # device (disk or partition)
  swapoff -a && swapon -a
fi

if systemctl is-active dphys-swapfile.service 2>&1 > /dev/null ; then
  # file
  dphys-swapfile swapoff && dphys-swapfile swapon
fi

#-------------------------------------------------------------------------------
# empty cache (2/2)
#-------------------------------------------------------------------------------
echo 3 > /proc/sys/vm/drop_caches

if [ "${DBG}" = "on" ] ; then
  ### after:
  echo "After:"
  swapon -s
  free -m
fi

exit 0
