Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swapsetup
#!/bin/sh
set -e
SWAPNAME="swapfile"
SWAPFILE="/var/swapfile.crypt"
MEMORY=`cat /proc/meminfo | grep MemTotal | sel -c 2`
# Next power of 2 Megabytes above reported memory
MEGABYTES=$(perl -e "use POSIX; print 2**ceil(log(ceil($MEMORY/(2**10)))/log(2))")
# status, on, or off
TYPE="$1"
if [ -z "$TYPE" ]; then
TYPE="on"
fi
enabled_p() {
SWAPS=$(sudo swapon -s | tail -n +2 | wc -l)
if [ $SWAPS -gt "0" ]; then
return 0;
else
return 1;
fi
}
status() {
# SWAPS=$(swapon -s | tail -n +2 | wc -l)
if enabled_p; then
swapon -s | tail -n +2 | sel -c 1 3 | xargs -n2 echo swap enabled
else
echo "swap disabled"
fi
}
cleanup() {
if [ -f /var/swap_loops ]; then
for loop_i in $(sudo cat /var/swap_loops); do
if sudo losetup "$loop_i" >/dev/null 2>&1; then
echo removing loopback $loop_i
sudo losetup -d "$loop_i"
fi
done
sudo rm /var/swap_loops
fi
if sh -c "sudo cryptsetup status $SWAPNAME >/dev/null 2>&1"; then
echo closing crypto $SWAPNAME
sudo cryptsetup close $SWAPNAME
fi
}
make_swapfile() {
echo "creating a swap of size ${MEGABYTES}mB"
sudo dd if=/dev/zero of=$SWAPFILE bs=1M count=$MEGABYTES
}
ensure_swapfile() {
if [ -f $SWAPFILE ]; then
SIZE=$(ls -l $SWAPFILE | sel -c 5)
MBACT=$(perl -e "use POSIX; print floor($SIZE/1048576)")
if [ "$MBACT" -lt "$MEGABYTES" ]; then
make_swapfile
fi
else
make_swapfile
fi
sudo chmod 600 $SWAPFILE
}
# run main operations
if [ "$TYPE" = "status" ]; then
status
elif [ "$TYPE" = "on" ]; then
if enabled_p; then
status
else
cleanup
ensure_swapfile
LOOP=$(sudo losetup -f)
echo using loopback device $LOOP
sudo sh -c "echo $LOOP >> /var/swap_loops"
sudo losetup $LOOP $SWAPFILE
echo setting up crypto
sudo cryptsetup open --type plain --key-file /dev/urandom $LOOP $SWAPNAME
echo mkswap on /dev/mapper/$SWAPNAME
sudo mkswap -f /dev/mapper/$SWAPNAME
echo swapon on /dev/mapper/$SWAPNAME
sudo swapon /dev/mapper/$SWAPNAME
status
fi
elif [ "$TYPE" = "off" ]; then
for swap_i in $(swapon -s | tail -n +2 | sel -c 1); do
echo swapoff on $swap_i
sudo swapoff $swap_i
done
cleanup
status
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.