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

if [[ "${EUID}" -ne 0 ]]; then
  echo "Run this script as root." >&2
  exit 1
fi

if [[ ! -r /etc/os-release ]]; then
  echo "Cannot determine operating system." >&2
  exit 1
fi

. /etc/os-release

if [[ "${ID:-}" != "debian" && "${ID:-}" != "ubuntu" ]]; then
  echo "This script supports Debian and Ubuntu guests only." >&2
  exit 1
fi

detect_vmware() {
  local virt=""

  if command -v systemd-detect-virt >/dev/null 2>&1; then
    virt="$(systemd-detect-virt 2>/dev/null || true)"
  fi

  if [[ "${virt}" == "vmware" ]]; then
    return 0
  fi

  if [[ -r /sys/class/dmi/id/sys_vendor ]] && grep -qi 'vmware' /sys/class/dmi/id/sys_vendor; then
    return 0
  fi

  return 1
}

configure_fsck_auto_repair() {
  # On systemd systems, fsck behavior is controlled via kernel cmdline.
  if [[ ! -f /etc/default/grub ]]; then
    echo "Skipping fsck auto-repair policy: /etc/default/grub not found."
    return 0
  fi

  if grep -Eq '^GRUB_CMDLINE_LINUX_DEFAULT="[^"]*fsck\.repair=' /etc/default/grub; then
    sed -i -E 's/(^GRUB_CMDLINE_LINUX_DEFAULT="[^"]*)fsck\.repair=[^" ]+([^"]*")/\1fsck.repair=yes\2/' /etc/default/grub
  elif grep -q '^GRUB_CMDLINE_LINUX_DEFAULT="' /etc/default/grub; then
    sed -i -E 's/^GRUB_CMDLINE_LINUX_DEFAULT="([^"]*)"/GRUB_CMDLINE_LINUX_DEFAULT="\1 fsck.repair=yes"/' /etc/default/grub
    sed -i -E 's/^GRUB_CMDLINE_LINUX_DEFAULT=" /GRUB_CMDLINE_LINUX_DEFAULT="/' /etc/default/grub
  else
    echo 'GRUB_CMDLINE_LINUX_DEFAULT="fsck.repair=yes"' >> /etc/default/grub
  fi

  if [[ -f /etc/default/rcS ]]; then
    if grep -q '^FSCKFIX=' /etc/default/rcS; then
      sed -i -E 's/^FSCKFIX=.*/FSCKFIX=yes/' /etc/default/rcS
    else
      echo 'FSCKFIX=yes' >> /etc/default/rcS
    fi
  fi

  if command -v update-grub >/dev/null 2>&1; then
    update-grub >/dev/null
  elif command -v grub-mkconfig >/dev/null 2>&1 && [[ -d /boot/grub ]]; then
    grub-mkconfig -o /boot/grub/grub.cfg >/dev/null
  else
    echo "Set fsck.repair=yes in /etc/default/grub; regenerate grub config manually." >&2
  fi

  echo "Configured fsck auto-repair policy (fsck.repair=yes) for next boot."
}

if ! detect_vmware; then
  echo "This system does not appear to be running on VMware." >&2
  exit 1
fi

export DEBIAN_FRONTEND=noninteractive

echo "Updating apt package index..."
apt-get update

echo "Installing open-vm-tools..."
apt-get install -y --no-install-recommends open-vm-tools

install -d -m 0755 /etc/sysctl.d
cat > /etc/sysctl.d/99-vmware-guest-tuning.conf <<'EOF'
# Conservative Debian guest tuning for VMware VPS instances.
vm.swappiness = 10
vm.dirty_background_ratio = 5
vm.dirty_ratio = 15
EOF

echo "Applying VMware guest sysctl tuning..."
sysctl --load /etc/sysctl.d/99-vmware-guest-tuning.conf

echo "Configuring fsck auto-repair policy..."
configure_fsck_auto_repair

if command -v systemctl >/dev/null 2>&1; then
  echo "Enabling open-vm-tools service..."
  systemctl enable --now open-vm-tools.service

  if systemctl list-unit-files --type=timer --no-legend 2>/dev/null | grep -q '^fstrim.timer'; then
    echo "Enabling fstrim.timer..."
    systemctl enable --now fstrim.timer
  fi
else
  echo "systemctl is unavailable; open-vm-tools was installed but not enabled." >&2
  exit 1
fi

echo "VMware guest optimization complete."
