#!/usr/bin/bash
# Prepares a host for k3s with a separate data disk: bind-mounts <data dir> on /var/lib/rancher, labels it for
# SELinux, opens firewalld for the pod and service networks and loads the sysctl settings.
# Run by the squirro-k3s-host package (%post) and by hand later. Safe to run again.
set -u

DATA_DIR="${SQ_K3S_DATA_DIR:-}"
DRY_RUN=false
K3S_DIR=/var/lib/rancher
FSTAB="${SQ_FSTAB:-/etc/fstab}"        # overridable for tests only

usage() {
  cat <<USAGE
Usage: squirro-k3s-prepare [--data-dir DIR] [--dry-run] [--help]

Without a data directory this only prints what to do. The data directory comes from --data-dir or from the
environment variable SQ_K3S_DATA_DIR. With one it:
  1. creates DIR and $K3S_DIR
  2. adds a bind mount DIR -> $K3S_DIR to $FSTAB (once) and mounts it
  3. restores SELinux labels on $K3S_DIR
  4. if firewalld runs: trusts the pod and service networks (10.42.0.0/16, 10.43.0.0/16), allows http and https
  5. loads the sysctl settings (vm.max_map_count for OpenSearch)
It refuses if $K3S_DIR already holds data and is not a mount, and never replaces a different mount.
--dry-run prints the changes without making them.
USAGE
}

instructions() {
  cat <<TXT
squirro-k3s-host: no data directory given (SQ_K3S_DATA_DIR is not set), the host was not changed.

To put the k3s data on a separate disk, mounted at /app/rancher for example, run this BEFORE k3s or
k3s-airgap-images write anything to $K3S_DIR:

  sudo SQ_K3S_DATA_DIR=/app/rancher squirro-k3s-prepare            # or add --dry-run first

or, when you install the packages, in one go:

  sudo SQ_K3S_DATA_DIR=/app/rancher dnf install squirro-k3s-host k3s k3s-selinux k3s-airgap-images

By hand that is:

  sudo mkdir -p /app/rancher $K3S_DIR
  echo '/app/rancher $K3S_DIR none bind,x-systemd.requires-mounts-for=/app 0 0' | sudo tee -a $FSTAB
  sudo systemctl daemon-reload && sudo mount $K3S_DIR && sudo restorecon -R $K3S_DIR
  # firewalld only: pod and service networks, web ports
  sudo firewall-cmd --permanent --zone=trusted --add-source=10.42.0.0/16 --add-source=10.43.0.0/16
  sudo firewall-cmd --permanent --add-service=http --add-service=https && sudo firewall-cmd --reload
  sudo sysctl --system

Not part of this package: /etc/rancher/k3s/registries.yaml (your registry mirror and its credentials).
TXT
}

log()  { echo "squirro-k3s-prepare: $*"; }
warn() { echo "squirro-k3s-prepare: WARNING: $*" >&2; }
die()  { echo "squirro-k3s-prepare: $*" >&2; exit 1; }
run() {
  if $DRY_RUN; then echo "squirro-k3s-prepare: [dry-run] $*"; return 0; fi
  log "$*"
  "$@"
}

while [ $# -gt 0 ]; do
  case "$1" in
    --data-dir) [ $# -ge 2 ] || die "--data-dir needs a directory"; DATA_DIR="$2"; shift 2 ;;
    --data-dir=*) DATA_DIR="${1#*=}"; shift ;;
    --dry-run) DRY_RUN=true; shift ;;
    --help|-h) usage; exit 0 ;;
    *) usage >&2; die "unknown argument $1" ;;
  esac
done

if [ -z "$DATA_DIR" ]; then instructions; exit 0; fi

# --- checks (nothing is changed before all of them passed) ---
case "$DATA_DIR" in /*) ;; *) die "data directory must be an absolute path: $DATA_DIR" ;; esac
case "$DATA_DIR" in *[[:space:]]*) die "data directory must not contain whitespace: $DATA_DIR" ;; esac
DATA_DIR="$(realpath -m "$DATA_DIR")"
case "$DATA_DIR" in "$K3S_DIR"|"$K3S_DIR"/*|/) die "data directory must be outside of $K3S_DIR (and not /): $DATA_DIR" ;; esac
$DRY_RUN && log "dry run: nothing is changed"

# an existing mount on /var/lib/rancher
if mountpoint -q "$K3S_DIR" 2>/dev/null; then
  if [ -d "$DATA_DIR" ] && [ "$(stat -c %d:%i "$DATA_DIR")" = "$(stat -c %d:%i "$K3S_DIR")" ]; then
    MOUNTED=same
  else
    die "$K3S_DIR is already a mount point of something else ($(findmnt -n -o SOURCE "$K3S_DIR" 2>/dev/null)), not touching it"
  fi
else
  MOUNTED=no
  if [ -d "$K3S_DIR" ] && [ -n "$(ls -A "$K3S_DIR" 2>/dev/null)" ]; then
    cat >&2 <<TXT
squirro-k3s-prepare: $K3S_DIR already has content and is not a mount point: k3s or k3s-airgap-images were
installed before the data disk was set up. Not changing anything (firewalld and sysctl are left alone too).
To move the data:
  sudo systemctl stop k3s && sudo k3s-killall.sh   # if k3s runs: stops it and its pods
  sudo mkdir -p $DATA_DIR
  sudo rsync -aHAX $K3S_DIR/ $DATA_DIR/
  sudo mv $K3S_DIR $K3S_DIR.old  # delete it once k3s works again
  sudo mkdir $K3S_DIR && sudo SQ_K3S_DATA_DIR=$DATA_DIR squirro-k3s-prepare
TXT
    exit 1
  fi
fi

# an fstab line for /var/lib/rancher that is not ours
FSTAB_HAS=no
if [ -f "$FSTAB" ]; then
  line="$(awk -v t="$K3S_DIR" '$1 !~ /^#/ && $2 == t {print; exit}' "$FSTAB")"
  if [ -n "$line" ]; then
    if [ "$(echo "$line" | awk '{print $1}')" = "$DATA_DIR" ]; then FSTAB_HAS=yes
    else die "$FSTAB already has a different entry for $K3S_DIR: $line"; fi
  fi
fi

# --- changes ---
run mkdir -p "$DATA_DIR" "$K3S_DIR"

if [ "$(stat -c %d "$DATA_DIR")" = "$(stat -c %d /)" ]; then
  warn "$DATA_DIR is on the same filesystem as /: the k3s data will not be on a separate disk"
  REQ=""
else
  MP="$(findmnt -n -o TARGET --target "$DATA_DIR" 2>/dev/null || true)"
  REQ="${MP:+,x-systemd.requires-mounts-for=$MP}"
fi

if [ "$FSTAB_HAS" = yes ]; then
  log "$FSTAB already has the bind mount"
elif $DRY_RUN; then
  echo "squirro-k3s-prepare: [dry-run] append to $FSTAB: $DATA_DIR $K3S_DIR none bind$REQ 0 0"
else
  log "append to $FSTAB: $DATA_DIR $K3S_DIR none bind$REQ 0 0"
  printf '# k3s data on the data disk (squirro-k3s-host)\n%s %s none bind%s 0 0\n' "$DATA_DIR" "$K3S_DIR" "$REQ" >> "$FSTAB"
fi

if [ -d /run/systemd/system ] && command -v systemctl >/dev/null; then run systemctl daemon-reload; fi
if [ "$MOUNTED" = same ]; then log "$K3S_DIR is already mounted from $DATA_DIR"; else run mount "$K3S_DIR"; fi
if command -v restorecon >/dev/null; then run restorecon -R "$K3S_DIR"; else log "restorecon not installed, skipping SELinux labels"; fi

if [ -d /run/systemd/system ] && systemctl is-active --quiet firewalld 2>/dev/null; then
  run firewall-cmd --quiet --permanent --zone=trusted --add-source=10.42.0.0/16 --add-source=10.43.0.0/16
  run firewall-cmd --quiet --permanent --add-service=http --add-service=https
  run firewall-cmd --quiet --reload
else
  log "firewalld is not active, firewall unchanged"
fi

if command -v sysctl >/dev/null; then run sysctl --system >/dev/null; fi
log "done"
