#!/bin/sh
# Install capsule on a Linux host, in one line:
#
#   curl -fsSL https://runcapsule.io/install.sh | sudo sh
#
# It works out the machine, downloads the latest release from GitHub, checks
# the archive against the release's SHA-256 list, installs the packages
# capsule's features use, and runs the installer that is in the archive
# (dist/install.sh). Run it again to upgrade.
#
#   ... | sudo sh -s -- remove            take capsule off, keep settings and data
#   ... | sudo sh -s -- remove --purge    take capsule off with settings and data
#
#   CAPSULE_VERSION=0.16.0   a release other than the latest
#   CAPSULE_DEPS=no          leave the distribution's packages alone
#
# What the check is worth: it shows the archive is the one the release lists
# and arrived whole. Both come from GitHub over HTTPS, so it does not protect
# against GitHub or this account being taken over.
set -eu

REPO=https://github.com/efops/capsule

say() { printf '%s\n' "$*"; }
die() { printf 'capsule install: %s\n' "$*" >&2; exit 1; }

fetch() { # fetch URL FILE
  if command -v curl >/dev/null 2>&1; then curl -fsSL --retry 3 -o "$2" "$1"
  elif command -v wget >/dev/null 2>&1; then wget -q -O "$2" "$1"
  else die "needs curl or wget"; fi
}

packages() {
  [ "${CAPSULE_DEPS:-yes}" = no ] && return 0
  id=; like=
  if [ -r /etc/os-release ]; then
    id=$(. /etc/os-release; printf '%s' "${ID:-}")
    like=$(. /etc/os-release; printf '%s' "${ID_LIKE:-}")
  fi
  case " $id $like " in
    *" debian "*|*" ubuntu "*)
      say "installing packages: uidmap wireguard-tools cryptsetup-bin e2fsprogs nftables curl dbus-user-session"
      export DEBIAN_FRONTEND=noninteractive
      # Just after a boot the unattended upgrade often holds apt's lock: wait for it, up to three minutes.
      apt-get -o DPkg::Lock::Timeout=180 update -qq || true
      apt-get -o DPkg::Lock::Timeout=180 install -y -qq uidmap wireguard-tools cryptsetup-bin e2fsprogs nftables curl dbus-user-session ;;
    *" fedora "*)
      case " $id $like " in
        *" rhel "*|*" centos "*)
          say "installing packages: epel-release shadow-utils wireguard-tools cryptsetup e2fsprogs nftables tar"
          dnf install -y -q epel-release || true ;;
        *) say "installing packages: shadow-utils wireguard-tools cryptsetup e2fsprogs nftables tar" ;;
      esac
      dnf install -y -q shadow-utils wireguard-tools cryptsetup e2fsprogs nftables tar ;;
    *" rhel "*|*" centos "*)
      say "installing packages: epel-release shadow-utils wireguard-tools cryptsetup e2fsprogs nftables tar"
      dnf install -y -q epel-release || true
      dnf install -y -q shadow-utils wireguard-tools cryptsetup e2fsprogs nftables tar ;;
    *" suse "*|*" opensuse "*)
      say "installing packages: shadow wireguard-tools cryptsetup e2fsprogs nftables tar gzip"
      zypper --non-interactive --quiet install shadow wireguard-tools cryptsetup e2fsprogs nftables tar gzip ;;
    *" alpine "*)
      say "installing packages: shadow-uidmap wireguard-tools cryptsetup e2fsprogs nftables util-linux"
      apk add --quiet shadow-uidmap wireguard-tools cryptsetup e2fsprogs nftables util-linux ;;
    *)
      say "this distribution is not one capsule knows the packages of; see docs/INSTALL.md for what its features need" ;;
  esac
}

main() {
  action=install; purge=
  for a in "$@"; do
    case "$a" in
      install) action=install ;;
      remove|uninstall) action=remove ;;
      --purge) purge=--purge ;;
      *) die "unknown argument: $a (use: install, remove, remove --purge)" ;;
    esac
  done

  [ "$(uname -s)" = Linux ] || die "capsule runs on Linux; this is $(uname -s)"
  [ "$(id -u)" = 0 ] || die "run it as root:  curl -fsSL https://runcapsule.io/install.sh | sudo sh"
  case "$(uname -m)" in
    x86_64|amd64) arch=amd64 ;;
    aarch64|arm64) arch=arm64 ;;
    *) die "no release for this machine ($(uname -m)); capsule is built for x86-64 and arm64" ;;
  esac
  command -v tar >/dev/null 2>&1 || [ "$action" = install ] || die "needs tar"
  command -v sha256sum >/dev/null 2>&1 || die "needs sha256sum"

  version=${CAPSULE_VERSION:-}
  if [ "$action" = remove ] && [ -z "$version" ] && command -v capsule >/dev/null 2>&1; then
    # Remove with the release that is installed, so its own list of what it put there is used.
    version=$(capsule version 2>/dev/null | sed -n 's/^capsule \([0-9][0-9.]*\).*/\1/p' | head -n 1)
  fi
  version=${version#v}
  if [ -n "$version" ]; then base=$REPO/releases/download/v$version; else base=$REPO/releases/latest/download; fi

  tmp=$(mktemp -d)
  trap 'rm -rf "$tmp"' EXIT INT TERM
  cd "$tmp"

  if [ "$action" = install ]; then
    case "$(stat -fc %T /sys/fs/cgroup 2>/dev/null || true)" in
      cgroup2fs) ;;
      *) say "warning: this host does not have cgroup v2 at /sys/fs/cgroup; capsule will not run programs until it does (see docs/INSTALL.md)" ;;
    esac
    packages || say "warning: some packages could not be installed; capsule itself is installed all the same, and docs/INSTALL.md says which feature needs which"
    command -v tar >/dev/null 2>&1 || die "needs tar"
  fi

  fetch "$base/SHA256SUMS" SHA256SUMS || die "could not download the release list from $base"
  line=$(grep "  capsule-[0-9][0-9.]*-linux-$arch\.tar\.gz\$" SHA256SUMS | head -n 1) || true
  [ -n "$line" ] || die "the release has no archive for linux-$arch"
  file=${line##*  }
  dir=${file%.tar.gz}
  say "downloading $file"
  fetch "$base/$file" "$file" || die "could not download $file"
  printf '%s\n' "$line" | sha256sum -c - >/dev/null 2>&1 || die "$file does not match the release's SHA-256; nothing was installed"
  say "checked against the release's SHA-256"
  # An archive made on macOS carries notes GNU tar warns about; only a real failure is shown.
  tar -xzf "$file" 2>tar.err || { cat tar.err >&2; die "could not unpack $file"; }
  [ -f "$dir/capsule" ] && [ -f "$dir/dist/install.sh" ] || die "the archive is not laid out as expected"

  if [ "$action" = remove ]; then
    sh "$dir/dist/uninstall.sh" $purge
    exit 0
  fi

  sh "$dir/dist/install.sh" "$dir/capsule"
  say ""
  say "Next:"
  say "  capsule keygen dev && sudo cp dev.pub /etc/capsule/trust.d/    a signing key this host trusts"
  say "  $REPO/blob/main/docs/GUIDE.md    the guide, from the first run on"
  who=${SUDO_USER:-}
  if [ -n "$who" ] && [ "$who" != root ] && getent group capsule >/dev/null 2>&1; then
    say "  sudo usermod -aG capsule $who    to use fast tunnels, sized volumes and low ports without root"
  fi
}

# Everything is inside main, called on the last line, so that a download cut
# short runs nothing.
main "$@"
