#!/usr/bin/env bash
set -euo pipefail

if [ "$(id -u)" -ne 0 ]; then
  echo "Jalankan sebagai root."
  exit 1
fi

read -rp "Ukuran swap, contoh 1G/2G/4G [2G]: " SWAP_SIZE
SWAP_SIZE="${SWAP_SIZE:-2G}"

if swapon --show | grep -q /swapfile; then
  echo "Swapfile sudah aktif."
  exit 0
fi

fallocate -l "$SWAP_SIZE" /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=2048
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab

echo "Swap aktif:"
swapon --show
