#!/usr/bin/env bash
# Enable a 4 GiB swap file, preserving existing files and active swap.
set -euo pipefail
export LC_ALL=C
[ "$(id -u)" -eq 0 ] || { echo 'Run as root.' >&2; exit 1; }
for cmd in swapon blkid df awk dd chmod mkswap sysctl; do
  command -v "$cmd" >/dev/null || { echo "Missing command: $cmd" >&2; exit 1; }
done
if ! swapon --noheadings --show=NAME | awk '$1 == "/swapfile" {found=1} END {exit !found}'; then
  if [ -e /swapfile ] || [ -L /swapfile ]; then
    [ -f /swapfile ] && [ ! -L /swapfile ] || { echo 'Refusing non-regular /swapfile.' >&2; exit 1; }
    [ "$(blkid -s TYPE -o value /swapfile || true)" = swap ] || { echo 'Existing /swapfile is not swap; leaving it untouched.' >&2; exit 1; }
    echo 'Reusing existing swap file at its current size.'
  else
    avail=$(df -Pk / | awk 'NR==2 {print $4}')
    [ "$avail" -ge 5242880 ] || { echo 'At least 5 GiB free disk space is required.' >&2; exit 1; }
    (umask 077; set -C; : > /swapfile)
    dd if=/dev/zero of=/swapfile bs=1M count=4096 conv=notrunc
    chmod 600 /swapfile
    mkswap /swapfile
  fi
  chmod 600 /swapfile
  swapon /swapfile || { echo 'Swap activation failed; startup configuration was not changed.' >&2; exit 1; }
fi
cp -p /etc/fstab "/etc/fstab.before-swap-$(date +%Y%m%d-%H%M%S)-$$"
if ! grep -qE '^[[:space:]]*/swapfile[[:space:]]' /etc/fstab; then
  printf '\n/swapfile none swap sw 0 0\n' >> /etc/fstab
fi
mkdir -p /etc/sysctl.d
if [ -e /etc/sysctl.d/zz-fast-swap.conf ]; then
  cp -p /etc/sysctl.d/zz-fast-swap.conf "/etc/sysctl.d/zz-fast-swap.conf.bak-$(date +%Y%m%d-%H%M%S)-$$"
fi
printf 'vm.swappiness = 10\n' > /etc/sysctl.d/zz-fast-swap.conf
sysctl -p /etc/sysctl.d/zz-fast-swap.conf
free -m
swapon --show
echo 'Swap enabled and startup configuration saved. No services restarted.'
