#!/bin/sh
# Vigilance for Linux (09 sections 3.1 and 4, LNX-05). The join page shows it as:
#
#   curl -fsSL https://check.vigihq.com/dl/linux/install.sh | sh -s -- <join code>
#
# Run as root (sudo, or a fleet tool), it installs the computer seat alone:
# one install for every account on this machine (00 section 22). Run as a
# person, it installs that person's seat, then may ask for sudo once for
# the administrator step below.
#
# As a person, it checks the system, downloads the program to
# ~/.cache/vigilance, checks it against the SHA-256 pinned below and runs it.
# The program then checks its signed manifest, writes ~/.vigi-seat and the
# systemd user units, joins, routes and prints the result. The first failed
# check prints one line and stops, and the script removes what it wrote.
#
# In Linux in WSL (09 3.6.2, LNX-19) the script also asks the Windows seat
# of the same Windows account for a link token and a port, through WSL
# interop. The Windows program answers on standard output, one key=value
# line each:
#
#   Vigilance.exe wsl-link --distro <name> [--not=<port>]...
#     exit 0: token=<token>, port=<port>, guid=<distro GUID>
#     exit 4 or 5: error=<code>
#     exit 2 and no error line: an older Windows program that has no
#     wsl-link command and prints its usage on standard error
#   Vigilance.exe wsl-link --done --guid <guid>    marks the distro linked
set -eu

BASE='https://check.vigihq.com'
VERSION='2.0.13'
SHA_ARM64='822cbda39df559a43fe0398f24419112981baf50c0dfe0ccf9c13e64e4bd15b0'
SHA_AMD64='e7e779a1d3c7bb899f7987832bd385d1e9dcd9b08059d1d8980181afd1344316'
PROTO='=https'

# Only the script tests set this: it moves /proc, /run, /etc and /mnt into a
# test folder, so a test can show each sign of WSL and of systemd. It can
# only make a check refuse or pass for the account that runs the script.
SYS=${VIGI_TEST_SYSROOT:-}

# printf, not echo: the echo of dash reads backslashes, and the WSL systemd
# line holds the text \n.
fail() {
  printf '%s\n' "$2" >&2
  exit "$1"
}

# Check 0: the arguments, in a loop, so the order does not matter and an
# argument the script does not know is never ignored.
code=
answer=
for a in "$@"; do
  case $a in
    --answer=mine | --answer=company) answer=${a#--answer=} ;;
    -*) fail 2 "Vigilance did not understand this command. Copy the command from your company's join page again." ;;
    *)
      [ -z "$code" ] || fail 2 "Vigilance did not understand this command. Copy the command from your company's join page again."
      code=$a
      ;;
  esac
done
[ -n "$code" ] || fail 2 "Vigilance needs the join code. Copy the command from your company's join page again."
root=0
[ "$(id -u)" != 0 ] || root=1
[ "$(uname -s)" = Linux ] || fail 2 "This command is for Linux. On a Mac or Windows, open the join link on that computer."
machine=$(uname -m)
case $machine in
  x86_64) arch=amd64 want=$SHA_AMD64 ;;
  aarch64) arch=arm64 want=$SHA_ARM64 ;;
  *) fail 2 "Vigilance runs on 64-bit Intel, AMD and Arm chips. This computer reports $machine, so Vigilance installed nothing." ;;
esac

# 09 5.13.1: any one sign is WSL. The first three do not depend on the
# kernel name, because a custom WSL kernel need not say microsoft. WSL 2.0
# and later also register WSLInterop-late, because systemd-binfmt can
# clear WSLInterop.
interop=0
if [ -e "$SYS/proc/sys/fs/binfmt_misc/WSLInterop" ] || [ -e "$SYS/proc/sys/fs/binfmt_misc/WSLInterop-late" ]; then
  interop=1
fi
wsl=0
if [ -n "${WSL_DISTRO_NAME:-}" ] || [ "$interop" = 1 ] || [ -e "$SYS/run/WSL" ]; then
  wsl=1
elif [ -r "$SYS/proc/sys/kernel/osrelease" ] && grep -qi microsoft "$SYS/proc/sys/kernel/osrelease"; then
  wsl=1
fi
distro=${WSL_DISTRO_NAME:-<distro>}
# Linux in WSL joins with its Windows computer, so it has no computer seat.
if [ "$root" = 1 ] && [ "$wsl" = 1 ]; then
  fail 2 "In Linux in WSL, run this as yourself, not with sudo. Vigilance comes with the Windows install."
fi

# W1: only the WSL 1 kernel name ends in -Microsoft. Any other kernel name
# in WSL counts as WSL 2, so a custom WSL 2 kernel is never refused.
if [ "$wsl" = 1 ]; then
  case $(cat "$SYS/proc/sys/kernel/osrelease" 2>/dev/null || true) in
    *-Microsoft) fail 2 "This is WSL 1. Vigilance needs WSL 2. To change it, run this in PowerShell: wsl --set-version $distro 2" ;;
  esac
fi

# Check 5: the units start at login only under a systemd user manager.
# 240 is the oldest systemd whose user units the program writes run as
# written.
nosystemd="Vigilance needs a systemd user session to start at each login. This system has none, so Vigilance installed nothing."
if [ "$wsl" = 1 ]; then
  # A second [boot] section would leave the first one's systemd line in
  # force, so the person edits the one that is there. wsl --shutdown is
  # never named: it also stops Docker Desktop and every other distro.
  if grep -qi '^[[:space:]]*\[boot\][[:space:]]*$' "$SYS/etc/wsl.conf" 2>/dev/null; then
    fix='Open /etc/wsl.conf as root. Under [boot], set systemd=true and delete any other systemd line.'
  else
    fix='Run this here:
  sudo sh -c '\''printf "\n[boot]\nsystemd=true\n" >> /etc/wsl.conf'\'''
  fi
  nosystemd="Vigilance needs systemd on in WSL. With systemd on, Linux starts its own system services. Programs set to start with Linux start too.
$fix
Then run this in PowerShell, and paste the command again:
  wsl --terminate $distro"
fi
[ -d "$SYS/run/systemd/system" ] || fail 2 "$nosystemd"
command -v systemctl >/dev/null 2>&1 || fail 2 "$nosystemd"
# Root has no user manager of its own. The computer seat needs only the
# system manager and the global user units of 240 and later.
[ "$root" = 1 ] || systemctl --user show-environment >/dev/null 2>&1 || fail 2 "$nosystemd"
sdver=$(systemctl --version 2>/dev/null | awk 'NR == 1 { for (i = 1; i <= NF; i++) if ($i ~ /^[0-9]+/) { sub(/[^0-9].*/, "", $i); print $i; exit } }') || sdver=
[ -n "$sdver" ] && [ "$sdver" -ge 240 ] || fail 2 "$nosystemd"

# W2 and W3 (09 5.13.4, 5.13.5): the Windows seat of this Windows account
# gives a single-use link token and a port. Only a live Windows device gets
# a token, so an uninstalled or removed Windows seat stops here.
noreach="Linux in WSL cannot reach Windows here, because WSL interop or the Windows drive mount is off. Run the Windows installer from your join page instead."
noseat="Install Vigilance on Windows first. Open your join link in a Windows browser. Then paste this command here again."
noport="Vigilance found no free port for Linux in WSL. Remove Vigilance from a distro you no longer use, then try again."
oldwin="Run the Windows installer from your join page again, then paste this command here again."
nots=
tries=0
# link asks the Windows seat for a token and a port, without the ports
# that were taken in here.
link() {
  out=$("$seat" wsl-link --distro "${WSL_DISTRO_NAME:-}" $nots 2>/dev/null) && rc=0 || rc=$?
  out=$(printf '%s\n' "$out" | tr -d '\r')
  token=$(printf '%s\n' "$out" | sed -n 's/^token=//p')
  port=$(printf '%s\n' "$out" | sed -n 's/^port=//p')
  guid=$(printf '%s\n' "$out" | sed -n 's/^guid=//p')
  if [ "$rc" = 0 ] && [ -n "$token" ] && [ -n "$port" ] && [ -n "$guid" ]; then
    return 0
  fi
  # The launcher passes on the exit code of the Windows program. An older
  # program does not know wsl-link and ends with its usage text, exit 2 and
  # no error line. That is a stale Windows install, not a network fault.
  case $(printf '%s\n' "$out" | sed -n 's/^error=//p') in
    '') [ "$rc" != 2 ] || fail 2 "$oldwin" ;;
    no_device | removed) fail 2 "$noseat" ;;
    wsl_closed) fail 2 "Vigilance does not run in Linux in WSL yet. Install Vigilance on Windows from your join page. Nothing was installed here." ;;
    wsl_full) fail 2 "This Windows computer already has Vigilance in 4 WSL distros. Remove it from one you no longer use, then try again." ;;
    no_port) fail 2 "$noport" ;;
    no_distro) fail 2 "$noreach" ;;
  esac
  fail 5 "Vigilance could not get a link from Windows. Check the internet connection and run the command again."
}
# taken reports a listener on the port inside WSL. All distros of one
# Windows account share one network stack. A reinstall keeps the port that
# its own filter holds. With no ss, the program's bind test decides (exit 7).
taken() {
  ! grep -qx "port = $port" "$HOME/.vigi-seat/config.toml" 2>/dev/null || return 1
  command -v ss >/dev/null 2>&1 || return 1
  ss -ltn 2>/dev/null | awk -v p=":$port" '{ if (substr($4, length($4) - length(p) + 1) == p) f = 1 } END { exit !f }'
}
# pick gets a token and a port that is free in here, at most 10 times.
pick() {
  while :; do
    link
    taken || return 0
    tries=$((tries + 1))
    [ "$tries" -lt 10 ] || fail 2 "$noport"
    nots="$nots --not=$port"
  done
}
if [ "$wsl" = 1 ]; then
  [ "$interop" = 1 ] || fail 2 "$noreach"
  cmdexe=$(command -v cmd.exe 2>/dev/null) || cmdexe=$SYS/mnt/c/Windows/System32/cmd.exe
  [ -x "$cmdexe" ] || fail 2 "$noreach"
  # cmd.exe started from a Linux folder warns on standard error that UNC
  # paths are not supported, and it ends its line with CRLF.
  winprofile=$("$cmdexe" /c echo %USERPROFILE% 2>/dev/null | tr -d '\r') || winprofile=
  case $winprofile in '' | *%*) fail 2 "$noreach" ;; esac
  winhome=$(wslpath -u "$winprofile" 2>/dev/null) || winhome=
  [ -n "$winhome" ] && [ -d "$winhome" ] || fail 2 "$noreach"
  seat=$winhome/.vigi-seat/Vigilance.exe
  [ -f "$seat" ] || fail 2 "$noseat"
  pick
fi

# Check 6: the restore check needs openssl for its ping and flock for its
# lock, so a missing one stops the install here, not later in the night.
missing=
for p in curl sha256sum openssl awk od cmp mktemp tail tr flock; do
  command -v "$p" >/dev/null 2>&1 || missing="${missing:+$missing, }$p"
done
[ -z "$missing" ] || fail 2 "Vigilance needs these programs: $missing. Install them with your package manager, then paste the command again."

# The download goes to the home folder, not /tmp: a hardened system mounts
# /tmp with noexec, and the program could not run from there.
cache_parent=$HOME/.cache
made_parent=0
[ -d "$cache_parent" ] || made_parent=1
cache=$cache_parent/vigilance
cleanup() {
  rm -rf "$cache"
  if [ "$made_parent" = 1 ]; then rmdir "$cache_parent" 2>/dev/null || true; fi
}
trap cleanup EXIT
trap 'exit 130' INT TERM
mkdir -p "$cache"
chmod 700 "$cache"
bin=$cache/vigi-seat
if ! curl -fsS --proto "$PROTO" -o "$bin" "$BASE/dl/seat/$VERSION/vigi-seat-linux-$arch"; then
  fail 5 "Vigilance did not get its program. Check the internet connection and run the command again."
fi
got=$(sha256sum "$bin" | cut -d ' ' -f 1)
[ "$got" = "$want" ] || fail 5 "The downloaded program is not the one this command expects, so Vigilance installed nothing."
chmod 700 "$bin"
# A home folder mounted noexec fails here, with a line the person can act on.
"$bin" version >/dev/null 2>&1 || fail 5 "Vigilance cannot run programs from your home folder. Ask your IT team, so Vigilance installed nothing."

# Standard input is this script, so the one question reads the keyboard.
if [ -z "$answer" ] && [ "$root" = 0 ]; then
  (exec </dev/tty) 2>/dev/null || fail 2 "Vigilance asks one question. Run the command in a terminal window."
fi

# install_once runs the program. The status is kept, not passed to exit at
# once, so the trap still removes the download.
install_once() {
  if [ "$wsl" = 1 ]; then
    set -- --link="$token" --port="$port"
  else
    set --
  fi
  rc=0
  if [ "$root" = 1 ]; then
    "$bin" computer install --join "$code" || rc=$?
  elif [ -n "$answer" ]; then
    "$bin" install --join "$code" --answer="$answer" "$@" || rc=$?
  else
    "$bin" install --join "$code" "$@" </dev/tty || rc=$?
  fi
}
if [ "$wsl" = 1 ]; then
  # With linger the user manager runs with no login session, so the filter
  # starts for "wsl.exe -e npm" too (09 5.13.6). A refusal does not stop
  # the install.
  loginctl enable-linger >/dev/null 2>&1 || true
fi
badlinks=0
while :; do
  install_once
  [ "$wsl" = 1 ] || break
  case $rc in
    7)
      # The port was taken after the check above.
      tries=$((tries + 1))
      [ "$tries" -lt 10 ] || fail 2 "$noport"
      nots="$nots --not=$port"
      pick
      ;;
    8)
      # The token was used, or it is older than 15 minutes: one new token.
      badlinks=$((badlinks + 1))
      [ "$badlinks" -lt 2 ] || fail 5 "The link to Windows expired. Run the command again."
      pick
      ;;
    *) break ;;
  esac
done
if [ "$wsl" = 1 ] && [ "$rc" = 0 ]; then
  "$seat" wsl-link --done --guid "$guid" >/dev/null 2>&1 ||
    printf '%s\n' "Vigilance is on here, but Windows did not record it. Run the Windows installer again to update the list."
fi
# The administrator step (1.2): only at a terminal, only for the company's
# computer, and only when the plan has the app check.
launcher=$HOME/.vigi-seat/Vigilance
if [ "$rc" = 0 ] && [ "$root" = 0 ] && [ "$wsl" = 0 ] && [ "$answer" != mine ] && [ -x "$launcher" ] &&
  (exec </dev/tty) 2>/dev/null && "$launcher" computer wanted >/dev/null 2>&1; then
  printf '%s\n' "Vigilance asks for your password once, so it can check every app on this computer for every user. It does not read your files."
  "$launcher" computer elevate --join "$code" </dev/tty || true
fi
exit "$rc"
