#!/bin/sh
# whichports agent installer, served at https://get.whichports.com:
#
#   curl -fsSL https://get.whichports.com | sh
#
# It configures the signed whichports package repository for your package
# manager and installs whichports-agent through it, so YOUR package manager
# verifies every byte against the published key before anything lands on
# disk. Nothing here starts a service: the timer stays off until you enable
# it, and the agent's stdout mode sends nothing anywhere.
#
# If you would rather not pipe a script into sh (a reasonable position), the
# repository setup below is short enough to do by hand; every step is plain
# to read here.
set -eu

BASE="https://get.whichports.com"
KEY_URL="$BASE/whichports-signing-public.asc"

[ "$(id -u)" = "0" ] || { echo "run as root (the package install needs it)" >&2; exit 1; }

if command -v apt-get >/dev/null 2>&1; then
  echo "* configuring the apt repository"
  # signed-by pins this repo to exactly our key, nothing system-wide.
  curl -fsSL "$KEY_URL" | gpg --dearmor -o /usr/share/keyrings/whichports.gpg
  echo "deb [signed-by=/usr/share/keyrings/whichports.gpg] $BASE/deb stable main" \
    > /etc/apt/sources.list.d/whichports.list
  apt-get update -o Dir::Etc::sourcelist=sources.list.d/whichports.list \
                 -o Dir::Etc::sourceparts=- -o APT::Get::List-Cleanup=0
  echo "* installing whichports-agent"
  apt-get install -y whichports-agent
elif command -v dnf >/dev/null 2>&1; then
  echo "* configuring the dnf repository"
  cat > /etc/yum.repos.d/whichports.repo <<EOF
[whichports]
name=whichports
baseurl=$BASE/rpm
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=$KEY_URL
EOF
  echo "* installing whichports-agent"
  dnf install -y whichports-agent
else
  echo "no apt or dnf found. Grab the package or static binary by hand:" >&2
  echo "  $BASE/deb/pool/main/    (deb)" >&2
  echo "  $BASE/rpm/              (rpm)" >&2
  exit 1
fi

echo
echo "installed. Next steps:"
echo "  one shot:   whichports-agent --mode=stdout"
echo "  every 15m:  systemctl enable --now whichports-agent.timer"
echo "  document:   /var/lib/whichports/host.json"
