#!/usr/bin/env bash
# isn't filtering node installer.
#
#   curl -fsSL https://install.isnt.app | bash
#   curl -fsSL https://install.isnt.app | bash -s -- --check        (options go after "--")
#
#   bash install.sh [--uplink IFACE] [--cp URL] [--cp-ca FILE] [--package FILE-or-URL] [--token-file FILE]
#   bash install.sh --check [--uplink IFACE]     only check the host, change nothing
#   bash install.sh --uninstall                  remove the node
#
# What it does, in this order, stopping at the first problem:
#   1. checks the host without changing it (kernel, uplink, other filters, free marks and tables);
#   2. unpacks the node to /opt/isnt-node and enrolls it with a one-time token from the console;
#   3. starts it WATCHING ONLY: programs are attached to the uplink but pass every packet untouched;
#   4. checks that the host still reaches its gateway and the control plane, and rolls everything
#      back if it does not.
# Filtering starts later, by `isnt arm`: a trial that ends by itself unless `isnt confirm` follows.
set -euo pipefail

CP=https://cp.isnt.app
PACKAGE=https://install.isnt.app/isnt-node.tar.gz
UPLINK=""; TOKEN_FILE=""; CP_CA=""; ACTION=install
ROOT=/opt/isnt-node; ETC=/etc/isnt-node; STATE=/var/lib/isnt-node

while [[ $# -gt 0 ]]; do
  case $1 in
    --uplink) UPLINK=$2; shift 2 ;;
    --cp) CP=$2; shift 2 ;;
    --cp-ca) CP_CA=$2; shift 2 ;; # a control plane with a private CA
    --package) PACKAGE=$2; shift 2 ;;
    --token-file) TOKEN_FILE=$2; shift 2 ;;
    --check) ACTION=check; shift ;;
    --uninstall) ACTION=uninstall; shift ;;
    -h|--help) sed -n '2,19p' "$0" 2>/dev/null | sed 's/^# \{0,1\}//'; exit 0 ;;
    *) echo "unknown option $1" >&2; exit 2 ;;
  esac
done
say() { printf '\n== %s\n' "$*"; }
die() { echo "install: $*" >&2; exit 1; }
[[ $EUID -eq 0 ]] || die "run as root"

if [[ $ACTION == uninstall ]]; then
  [[ -x $ROOT/bin/isnt ]] || die "the node is not installed"
  exec "$ROOT/bin/isnt" uninstall
fi

# The interface the default route leaves through; for a bridge, its one port toward the network.
guess_uplink() {
  local dev; dev=$(ip route show default | awk '{for (i = 1; i < NF; i++) if ($i == "dev") {print $(i+1); exit}}')
  [[ -n $dev ]] || return 1
  if [[ -d /sys/class/net/$dev/bridge ]]; then
    local ports=() p
    for p in /sys/class/net/"$dev"/brif/*; do
      p=$(basename "$p")
      [[ -e /sys/class/net/$p/device || -d /sys/class/net/$p/bonding ]] && ports+=("$p")
    done
    [[ ${#ports[@]} -eq 1 ]] || return 1
    dev=${ports[0]}
  fi
  echo "$dev"
}
if [[ -z $UPLINK ]]; then
  UPLINK=$(guess_uplink) || die "cannot tell which interface is the uplink: pass --uplink IFACE"
  echo "uplink: $UPLINK (the default route's interface; --uplink overrides)"
fi

work=$(mktemp -d); trap 'rm -rf "$work"' EXIT
say "package"
if [[ $PACKAGE == http://* || $PACKAGE == https://* ]]; then
  curl -fsSL --retry 2 -o "$work/pkg.tar.gz" "$PACKAGE" || die "cannot download $PACKAGE"
  curl -fsSL --retry 2 -o "$work/pkg.sha256" "$PACKAGE.sha256" || die "cannot download $PACKAGE.sha256"
else
  [[ -r $PACKAGE && -r $PACKAGE.sha256 ]] || die "$PACKAGE and $PACKAGE.sha256 must both be readable"
  cp "$PACKAGE" "$work/pkg.tar.gz"; cp "$PACKAGE.sha256" "$work/pkg.sha256"
fi
[[ $(sha256sum < "$work/pkg.tar.gz" | awk '{print $1}') == $(awk '{print $1}' "$work/pkg.sha256") ]] || die "the package does not match its checksum"
mkdir "$work/pkg" && tar -xzf "$work/pkg.tar.gz" -C "$work/pkg"
for f in bin/agent bin/slowpath bin/isnt bpf/ingress.bpf.o isnt-agent.service isnt-slowpath.service VERSION; do
  [[ -e $work/pkg/$f ]] || die "the package is incomplete: $f is missing"
done
echo "version $(cat "$work/pkg/VERSION")"

say "host check"
if [[ -e $ROOT/bin/agent ]]; then
  bash "$work/pkg/bin/isnt" _check_installed "$UPLINK" || die "the host check failed: nothing was changed"
else
  bash "$work/pkg/bin/isnt" check "$UPLINK" || die "the host check failed: nothing was changed"
fi
[[ $ACTION == check ]] && exit 0

# From here on the host changes. Anything that fails undoes all of it.
upgrade=""; [[ -e $ROOT/bin/agent ]] && upgrade=1
rollback() {
  trap - ERR
  echo; echo "install: FAILED, undoing the installation" >&2
  systemctl disable --now isnt-slowpath isnt-agent >/dev/null 2>&1 || true
  if [[ -z $upgrade ]]; then
    "$ROOT/bin/isnt" uninstall >/dev/null 2>&1 || true
    echo "install: the host is as it was before" >&2
  else
    echo "install: the node is stopped (traffic is not filtered); the previous installation's files were replaced" >&2
  fi
  exit 1
}
trap rollback ERR

say "files"
systemctl stop isnt-slowpath isnt-agent 2>/dev/null || true
mkdir -p "$ROOT" "$ETC" "$STATE"; chmod 700 "$STATE"
rm -rf "$ROOT/bin" "$ROOT/bpf"
cp -r "$work/pkg/bin" "$work/pkg/bpf" "$work/pkg/VERSION" "$ROOT/"
chmod 755 "$ROOT"/bin/*
ln -sf "$ROOT/bin/isnt" /usr/local/bin/isnt
printf 'UPLINK=%s\n' "$UPLINK" > "$ETC/node.env"
cp "$work/pkg/isnt-agent.service" "$work/pkg/isnt-slowpath.service" /etc/systemd/system/
systemctl daemon-reload
# Always start watching only, an upgrade too: arming is a separate, deliberate step.
echo observe > "$STATE/mode"

if [[ ! -s $STATE/node.json ]]; then
  say "enrollment"
  tf=$work/token; umask 077
  if [[ -n $TOKEN_FILE ]]; then
    cp "$TOKEN_FILE" "$tf"
  elif [[ -n ${ISNT_JOIN_TOKEN:-} ]]; then
    printf '%s' "$ISNT_JOIN_TOKEN" > "$tf"
  else
    [[ -r /dev/tty ]] || { echo "no terminal to ask for the token: pass --token-file" >&2; false; }
    read -rsp "One-time enrollment token from the console (Nodes -> Add a node): " t < /dev/tty; echo
    printf '%s' "$t" > "$tf"; unset t
  fi
  "$ROOT/bin/agent" join --cp "$CP" ${CP_CA:+--cp-ca "$CP_CA"} --token-file "$tf" --state-dir "$STATE"
  rm -f "$tf"
else
  echo "already enrolled: keeping the node's credential"
fi

say "start (watching only)"
gw=$(ip route show default | awk '{print $3; exit}')
systemctl enable --now isnt-agent isnt-slowpath
for _ in $(seq 30); do
  journalctl -u isnt-agent -n 200 --no-pager -o cat --since "-2min" 2>/dev/null | grep -q "data plane attached" && break
  systemctl is-failed -q isnt-agent && break
  sleep 1
done
systemctl is-active -q isnt-agent || { journalctl -u isnt-agent -n 15 --no-pager -o cat >&2; echo "the agent did not start" >&2; false; }
journalctl -u isnt-agent -n 200 --no-pager -o cat --since "-2min" | grep -q "data plane attached" || { echo "the data plane did not attach" >&2; false; }
systemctl is-active -q isnt-slowpath || { journalctl -u isnt-slowpath -n 15 --no-pager -o cat >&2; echo "the slow path did not start" >&2; false; }

say "the host after the start"
if [[ -n $gw ]]; then ping -c3 -W2 -q "$gw" >/dev/null 2>&1 || { echo "the default gateway $gw stopped answering" >&2; false; }; echo "  ok    default gateway $gw answers"; fi
cph=${CP#*://}; cph=${cph%%/*}
[[ $cph == *:* ]] || cph=$cph:443
timeout 10 bash -c "exec 3<>/dev/tcp/${cph%:*}/${cph##*:}" 2>/dev/null || { echo "the control plane $cph is not reachable" >&2; false; }
echo "  ok    control plane $cph reachable"
trap - ERR

say "installed"
"$ROOT/bin/isnt" status
cat <<'TXT'

The node is WATCHING ONLY: nothing is filtered yet.
  1. In the console, check that the node is connected and add what it should protect.
  2. isnt arm        filtering for a 5 minute trial; it stops by itself
  3. isnt confirm    keep it on, once you have seen your services work
  isnt disarm stops filtering at once; isnt uninstall removes the node.
TXT
