#!/usr/bin/bash

if [ "$(id -u)" -ne 0 ]; then
  echo "Error: This script must be run with root privileges."
  exit 1
fi

file_path="/sys/kernel/mm/ksm/run"
conf_path="/etc/tmpfiles.d/ksm.conf"
save="y"

if [ "$#" -eq 0 ]; then
  echo "Usage: $0 [--unsave|-u] {--enable|-e|--disable|-d}"
  echo "  --enable , -e :  Enable KSM"
  echo "  --disable, -d : Disable KSM"
  echo "  --unsave, -u : Do not save choice to config files"
  exit 1
fi

while [[ "$#" -gt 0 ]]; do
    case "$1" in
      --enable | -e)
        new_state="1"
        shift
        ;;
      --disable | -d)
        new_state="0"
        shift
        ;;
      -u | --unsave)
        unset save
        shift
        ;;
      *)
        echo "Error: Invalid argument. Use --enable, -e, --disable, or -d." >&2
        exit 1
        ;;
    esac
done

if [ -z "$new_state" ]; then
    echo "Error: Missing action. Use --enable, -e, --disable, or -d." >&2
    exit 1
fi

if [ "$new_state" -gt 0 ]; then
    echo "Enabling Kernel Samepage Merging..."
    echo "1" > "$file_path"
else
    echo "Disabling Kernel Samepage Merging..."
    echo "2" > "$file_path"

fi

if [ -n "$save" ]; then
    echo "w! /sys/kernel/mm/ksm/run - - - - $new_state" > "$conf_path"
fi
