#!/bin/bash
# oxmc-platform: match this machine against rules.conf files and install the
# config files of the matching tweaks.
set -eu

SHARE=${OXMC_SHARE:-/usr/share/oxmc-platform}
LOCAL=${OXMC_LOCAL:-/etc/oxmc-platform}
STATE=${OXMC_STATE:-/var/lib/oxmc-platform}
DMI=${OXMC_DMI:-/sys/class/dmi/id}
SYS=${OXMC_SYS:-/sys}
PROC=${OXMC_PROC:-/proc}
ROOT=${OXMC_ROOT:-}
ARCH=${OXMC_ARCH:-$(uname -m 2>/dev/null || true)}
MANAGED=$STATE/managed

usage() {
  cat <<'USAGE'
Usage: oxmc-platform [--list | --explain | --clean]
  (no option)  detect this machine and install the matching tweaks
  --list       show detected facts and the tweaks that match, change nothing
  --explain    like --list, but show every rule and why it matched or not
  --clean      remove every file this tool installed
USAGE
}

mode=apply
case "${1:-}" in
  "")        ;;
  --list)    mode=list ;;
  --explain) mode=explain ;;
  --clean)   mode=clean ;;
  -h|--help) usage; exit 0 ;;
  *)         usage >&2; exit 2 ;;
esac

# run system-changing commands only on the real system (not in tests)
sysact() {
  if [ -z "$ROOT" ]; then "$@" || true; fi
}

clean_managed() {
  local f
  if [ ! -f "$MANAGED" ]; then return 0; fi
  while IFS= read -r f; do
    if [ -n "$f" ]; then rm -f -- "$ROOT$f"; fi
  done < "$MANAGED"
  : > "$MANAGED"
}

if [ "$mode" = clean ]; then clean_managed; exit 0; fi

# ---------------------------------------------------------------- facts
trim() {
  local s=$1
  s=${s#"${s%%[![:space:]]*}"}
  s=${s%"${s##*[![:space:]]}"}
  printf '%s' "$s"
}
dmi() { cat "$DMI/$1" 2>/dev/null || true; }

vendor=$(dmi sys_vendor)
product=$(dmi product_name)
version=$(dmi product_version)
chassis=$(dmi chassis_type)
ram_kb=$(awk '/^MemTotal:/{print $2}' "$PROC/meminfo" 2>/dev/null || true)
ram_mb=$(( ${ram_kb:-0} / 1024 ))
cpu_vendor=$(awk -F'[[:space:]]*:[[:space:]]*' '/^vendor_id/{print $2; exit}' "$PROC/cpuinfo" 2>/dev/null || true)

is_laptop() {
  local b
  for b in "$SYS"/class/power_supply/BAT* "$SYS"/class/power_supply/CMB*; do
    if [ -e "$b" ]; then return 0; fi
  done
  case "$chassis" in 8|9|10|11|14|30|31|32) return 0 ;; esac
  return 1
}

intel_wifi() {
  local d c v
  for d in "$SYS"/bus/pci/devices/*; do
    if [ ! -r "$d/class" ]; then continue; fi
    c=$(cat "$d/class" 2>/dev/null || true)
    v=$(cat "$d/vendor" 2>/dev/null || true)
    if [[ $c == 0x0280* && $v == 0x8086 ]]; then return 0; fi
  done
  return 1
}

cond_one() {
  local c f g
  c=$(trim "$1")
  case "$c" in
    ""|-)       return 0 ;;
    laptop)     is_laptop ;;
    desktop)    ! is_laptop ;;
    "ram<="*)   [ "$ram_mb" -le "${c#ram<=}" ] ;;
    "ram>"*)    [ "$ram_mb" -gt "${c#ram>}" ] ;;
    cpu=*)      [ "$cpu_vendor" = "${c#cpu=}" ] ;;
    wifi=intel) intel_wifi ;;
    arch=*)     [ "$ARCH" = "${c#arch=}" ] ;;
    dmi:*=*)
      f=${c#dmi:}; g=${f#*=}; f=${f%%=*}
      case "$f" in ""|*[!a-z_]*) return 1 ;; esac
      [[ "$(dmi "$f")" == $g ]]
      ;;
    *) echo "oxmc-platform: unknown condition '$c'" >&2; return 1 ;;
  esac
}

# all comma-separated conditions must hold
cond_all() {
  local parts part
  IFS=, read -ra parts <<<"$1"
  for part in ${parts[@]+"${parts[@]}"}; do
    cond_one "$part" || return 1
  done
  return 0
}

# ---------------------------------------------------------------- rules
rule_files=()
for f in "$SHARE"/*/rules.conf "$LOCAL/rules.conf" "$LOCAL"/rules.d/*.conf; do
  if [ -f "$f" ]; then rule_files+=("$f"); fi
done

if [ "$mode" != apply ]; then
  echo "vendor    : ${vendor:-?}"
  echo "product   : ${product:-?}"
  echo "version   : ${version:-?}"
  echo "chassis   : ${chassis:-?} ($(if is_laptop; then echo laptop; else echo desktop; fi))"
  echo "ram       : ${ram_mb} MB"
  echo "cpu       : ${cpu_vendor:-unknown}"
  echo "arch      : ${ARCH:-?}"
  echo "intel wifi: $(if intel_wifi; then echo yes; else echo no; fi)"
fi

selected=(); denied=()
for f in ${rule_files[@]+"${rule_files[@]}"}; do
  if [ "$mode" = explain ]; then echo "rules: $f"; fi
  while IFS='|' read -r t v p c || [ -n "${t:-}" ]; do
    t=$(trim "$t")
    if [ -z "$t" ]; then continue; fi
    case "$t" in \#*) continue ;; esac
    v=$(trim "${v:-}"); p=$(trim "${p:-}"); c=$(trim "${c:-}")
    why=""
    if ! [[ $vendor == ${v:-*} ]]; then
      why="vendor '$vendor' does not match '${v:-*}'"
    elif ! [[ $product == ${p:-*} ]]; then
      why="product '$product' does not match '${p:-*}'"
    elif ! cond_all "$c"; then
      why="condition '$c' is false"
    fi
    if [ "$mode" = explain ]; then
      if [ -z "$why" ]; then printf '  match  %s\n' "$t"; else printf '  skip   %-26s %s\n' "$t" "$why"; fi
    fi
    if [ -n "$why" ]; then continue; fi
    case "$t" in -*) denied+=("${t#-}") ;; *) selected+=("$t") ;; esac
  done < "$f"
done

final=()
for t in ${selected[@]+"${selected[@]}"}; do
  skip=0
  for d in ${denied[@]+"${denied[@]}"}; do if [ "$t" = "$d" ]; then skip=1; fi; done
  for d in ${final[@]+"${final[@]}"}; do if [ "$t" = "$d" ]; then skip=1; fi; done
  if [ "$skip" = 0 ]; then final+=("$t"); fi
done

if [ "$mode" != apply ]; then
  echo "tweaks    : ${final[*]:-none}"
  exit 0
fi

# ---------------------------------------------------------------- apply
find_tweak() {
  local t=$1 base
  for base in "$LOCAL/tweaks" "$SHARE"/*/tweaks; do
    if [ -d "$base/$t/files" ]; then printf '%s' "$base/$t/files"; return 0; fi
  done
  return 1
}

mkdir -p "$STATE"
clean_managed
: > "$MANAGED"
reload_sysctl=0; reload_systemd=0
tmpfiles=(); modfiles=()

for t in ${final[@]+"${final[@]}"}; do
  if ! src=$(find_tweak "$t"); then
    echo "oxmc-platform: tweak '$t' has no files directory, skipping" >&2
    continue
  fi
  while IFS= read -r -d '' file; do
    dest=/${file#"$src"/}
    if [ -e "$ROOT$dest" ]; then
      echo "oxmc-platform: $dest exists and is not ours, skipping ($t)" >&2
      continue
    fi
    install -D -m "$(stat -c %a "$file")" "$file" "$ROOT$dest"
    echo "$dest" >> "$MANAGED"
    case "$dest" in
      /etc/sysctl.d/*)       reload_sysctl=1 ;;
      /etc/tmpfiles.d/*)     tmpfiles+=("$dest") ;;
      /etc/modules-load.d/*) modfiles+=("$dest") ;;
      /etc/systemd/*|/usr/lib/systemd/*) reload_systemd=1 ;;
    esac
  done < <(find "$src" -type f -print0)
done

if [ "$reload_sysctl" = 1 ]; then sysact sysctl -q --system; fi
if [ "${#tmpfiles[@]}" -gt 0 ]; then sysact systemd-tmpfiles --create "${tmpfiles[@]}"; fi
if [ "${#modfiles[@]}" -gt 0 ]; then
  for p in /usr/lib/systemd/systemd-modules-load /lib/systemd/systemd-modules-load; do
    if [ -x "$p" ]; then sysact "$p" "${modfiles[@]}"; break; fi
  done
fi
if [ "$reload_systemd" = 1 ]; then sysact systemctl daemon-reload; fi

msg="applied: ${final[*]:-none} (${vendor:-?} / ${product:-?}, ${ram_mb} MB)"
echo "oxmc-platform: $msg"
logger -t oxmc-platform -- "$msg" 2>/dev/null || true
