#!/bin/sh
# Nocward Monitoring agent - installer for Linux (systemd).
#
#   curl -fsSL https://dl.nocward.com/pub/nocward-monitoring-agent/latest/install.sh | sudo sh -s -- \
#       --url https://nms.example.com/api --key <agent key> --device <device id>
#
# Picks the .deb (Debian/Ubuntu), the .rpm (RHEL/Rocky/Alma/Fedora/SUSE) or
# the tar.gz (anything else with systemd) for this machine's architecture,
# downloads it from this release's own folder, checks its SHA-256 against
# the sums built into this script and the folder's SHA256SUMS,
# installs it, writes the settings and starts the agent. Run it again to
# upgrade (settings are kept). From an unpacked tar.gz it installs the
# binary next to it. Options:
#
#   --url URL --key KEY --device ID   connection (see docs/AGENTS.md)
#   --pin sha256//...                 the server's public-key pin (self-signed certificate)
#   --ca-file FILE                    CA of the server's certificate (copied to /etc/nocward-agent/ca.pem)
#   --proxy URL                       HTTP(S) proxy for the pushes
#   --interval SECONDS                push interval (default 60)
#   --method auto|deb|rpm|tar         package type (default: auto)
#   --download-base URL               where the release files are (default below)
#   --uninstall [--purge]             remove the agent (--purge: also its settings and buffer)
set -eu

VERSION="1.4.0"
DOWNLOAD_BASE="${NOCWARD_DOWNLOAD_BASE:-https://dl.nocward.com/pub/nocward-monitoring-agent/1.4.0}"
# SHA-256 of this release's files, filled in when the release is built.
SUMS='9e336f9a41c1d329390629d6f8dfc91bba4d1916d1642903d899b2c7cc02b8a4  nocward-monitoring-agent-1.4.0-amd64.deb
2afc0ec320c0a15b5f34339876140cb8912395e6df1ac96b67bd6bfe4e72853a  nocward-monitoring-agent-1.4.0-arm64.deb
6f0c95183a39b14277b39ecf4cdfd3ec10496a77a7185b1eedb1b81dbc194e46  nocward-monitoring-agent-1.4.0.aarch64.rpm
f73be12c1f17db4eabdbbde581af37f387cc15f453092da1193a01a69d54b499  nocward-monitoring-agent-1.4.0.x86_64.rpm
53d1b7632f594e8ae974fac6366ed8f995cb49b87e13ad2f515420da4323081c  nocward-monitoring-agent-1.4.0-linux-amd64.tar.gz
45ef7312e0b1439a0414217cbd71a8b9a73c1527ca205cbb2a8416f44adb5a6d  nocward-monitoring-agent-1.4.0-linux-arm64.tar.gz'

say() { printf 'nocward-agent: %s\n' "$*"; }
die() { printf 'nocward-agent: ERROR: %s\n' "$*" >&2; exit 1; }

URL="" KEY="" DEVICE="" PIN="" CA_FILE="" PROXY="" INTERVAL="" METHOD="auto" UNINSTALL=0 PURGE=0
while [ $# -gt 0 ]; do
    case "$1" in
        --url) URL="${2:-}"; shift 2 ;;
        --key) KEY="${2:-}"; shift 2 ;;
        --device) DEVICE="${2:-}"; shift 2 ;;
        --pin) PIN="${2:-}"; shift 2 ;;
        --ca-file) CA_FILE="${2:-}"; shift 2 ;;
        --proxy) PROXY="${2:-}"; shift 2 ;;
        --interval) INTERVAL="${2:-}"; shift 2 ;;
        --method) METHOD="${2:-}"; shift 2 ;;
        --download-base) DOWNLOAD_BASE="${2:-}"; shift 2 ;;
        --uninstall) UNINSTALL=1; shift ;;
        --purge) PURGE=1; shift ;;
        -h|--help) sed -n '2,25p' "$0" 2>/dev/null || true; exit 0 ;;
        *) die "unknown option $1 (see --help)" ;;
    esac
done

[ "$(id -u)" -eq 0 ] || die "run as root (sudo)"

case "$(uname -m)" in
    x86_64|amd64) ARCH=amd64 RPMARCH=x86_64 ;;
    aarch64|arm64) ARCH=arm64 RPMARCH=aarch64 ;;
    *) die "unsupported architecture $(uname -m) (amd64 and arm64 are built)" ;;
esac

# The folder this script is in, when it is a file (not piped into sh).
HERE=""
case "$0" in
    */install.sh|install.sh) [ -f "$0" ] && HERE="$(cd "$(dirname "$0")" && pwd)" ;;
esac

installed_by() {
    if command -v dpkg-query >/dev/null 2>&1 && dpkg-query -W -f='${Status}' nocward-agent 2>/dev/null | grep -q "install ok installed"; then
        echo deb
    elif command -v rpm >/dev/null 2>&1 && rpm -q nocward-agent >/dev/null 2>&1; then
        echo rpm
    elif [ -f /usr/lib/nocward-agent/installed-from-tar ]; then
        echo tar
    fi
}

systemd_running() { command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; }

# ---------------------------------------------------------------- uninstall
if [ "$UNINSTALL" -eq 1 ]; then
    how="$(installed_by)"
    case "$how" in
        deb) if [ "$PURGE" -eq 1 ]; then dpkg --purge nocward-agent; else dpkg --remove nocward-agent; fi ;;
        rpm) rpm -e nocward-agent ;;
        tar)
            if systemd_running; then
                for unit in nocward-agent nocward-docker-proxy; do
                    systemctl disable --now "$unit" >/dev/null 2>&1 || true
                done
            fi
            rm -f /usr/bin/nocward-agent /etc/systemd/system/nocward-agent.service \
                /etc/systemd/system/nocward-docker-proxy.service
            rm -rf /usr/lib/nocward-agent /var/lib/nocward-agent
            systemd_running && systemctl daemon-reload || true
            ;;
        *) say "the agent is not installed"; exit 0 ;;
    esac
    if [ "$PURGE" -eq 1 ]; then
        rm -rf /etc/nocward-agent /var/lib/nocward-agent
        userdel nocward-agent >/dev/null 2>&1 || true
        groupdel nocward-agent >/dev/null 2>&1 || true
    fi
    say "removed ($how)$( [ "$PURGE" -eq 1 ] && echo ', settings deleted' || echo ', settings kept in /etc/nocward-agent')"
    exit 0
fi

# ------------------------------------------------------------------ install
systemd_running || die "this installer needs systemd (start the binary by hand on other init systems, see docs/AGENTS.md)"

if [ "$METHOD" = auto ]; then
    current="$(installed_by)"
    if [ -n "$current" ]; then
        METHOD="$current"
    elif [ -n "$HERE" ] && [ -x "$HERE/nocward-agent" ]; then
        METHOD=tar
    elif command -v dpkg >/dev/null 2>&1 && command -v apt-get >/dev/null 2>&1; then
        METHOD=deb
    elif command -v rpm >/dev/null 2>&1 && { command -v dnf >/dev/null 2>&1 || command -v yum >/dev/null 2>&1 || command -v zypper >/dev/null 2>&1; }; then
        METHOD=rpm
    else
        METHOD=tar
    fi
fi
case "$METHOD" in
    deb) FILE="nocward-monitoring-agent-${VERSION}-${ARCH}.deb" ;;
    rpm) FILE="nocward-monitoring-agent-${VERSION}.${RPMARCH}.rpm" ;;
    tar) FILE="nocward-monitoring-agent-${VERSION}-linux-${ARCH}.tar.gz" ;;
    *) die "--method must be auto, deb, rpm or tar" ;;
esac

sha256() {
    if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
    else openssl dgst -sha256 "$1" | sed 's/.*= *//'; fi
}

TMP="$(mktemp -d)"
chmod 755 "$TMP"   # apt reads the package as its own _apt user
trap 'rm -rf "$TMP"' EXIT INT TERM

SRC=""
if [ "$METHOD" = tar ] && [ -n "$HERE" ] && [ -x "$HERE/nocward-agent" ]; then
    SRC="$HERE"   # an unpacked tar.gz: install what is next to this script
else
    if [ -n "$HERE" ] && [ -f "$HERE/$FILE" ]; then
        cp "$HERE/$FILE" "$TMP/$FILE"
    else
        fetch() {
            if command -v curl >/dev/null 2>&1; then
                curl -fsSL --retry 3 -o "$TMP/$1" "$DOWNLOAD_BASE/$1" || die "download failed: $DOWNLOAD_BASE/$1"
            elif command -v wget >/dev/null 2>&1; then
                wget -q -O "$TMP/$1" "$DOWNLOAD_BASE/$1" || die "download failed: $DOWNLOAD_BASE/$1"
            else
                die "curl or wget is needed"
            fi
        }
        say "downloading $FILE"
        fetch "$FILE"
        # the release folder's own SHA256SUMS must agree as well
        fetch SHA256SUMS
        listed="$(awk -v f="$FILE" '$2 == f || $2 == "*"f {print $1}' "$TMP/SHA256SUMS")"
        [ "$listed" = "$(sha256 "$TMP/$FILE")" ] || die "$FILE does not match the release's SHA256SUMS - not installed"
    fi
    want="$(printf '%s\n' "$SUMS" | awk -v f="$FILE" '$2 == f || $2 == "*"f {print $1}')"
    [ -n "$want" ] || die "no SHA-256 known for $FILE in this installer"
    got="$(sha256 "$TMP/$FILE")"
    [ "$got" = "$want" ] || die "SHA-256 mismatch for $FILE (expected $want, got $got) - not installed"
    say "SHA-256 verified: $FILE"
fi

host_setup() {
    getent group nocward-agent >/dev/null 2>&1 || groupadd -r nocward-agent
    getent passwd nocward-agent >/dev/null 2>&1 || useradd -r -g nocward-agent -d /var/lib/nocward-agent -M \
        -s /usr/sbin/nologin -c "Nocward Monitoring agent" nocward-agent
    getent group systemd-journal >/dev/null 2>&1 && usermod -a -G systemd-journal nocward-agent || true
    install -d -m 0750 -o nocward-agent -g nocward-agent /var/lib/nocward-agent
    install -d -m 0755 /etc/nocward-agent /etc/nocward-agent/scripts.d
    [ -f /etc/nocward-agent/agent.env ] || install -m 0600 /etc/nocward-agent/agent.env.example /etc/nocward-agent/agent.env
    chmod 0600 /etc/nocward-agent/agent.env
}

case "$METHOD" in
    deb)
        # apt-get waits for the package lock (another install running);
        # keep changed config files, never ask
        if command -v apt-get >/dev/null 2>&1; then
            DEBIAN_FRONTEND=noninteractive apt-get install -y -q --reinstall --allow-downgrades -o DPkg::Lock::Timeout=300                 -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold "$TMP/$FILE" </dev/null
        else
            DEBIAN_FRONTEND=noninteractive dpkg -i --force-confdef --force-confold "$TMP/$FILE" </dev/null
        fi
        ;;
    rpm) rpm -U --replacepkgs "$TMP/$FILE" </dev/null ;;
    tar)
        if [ -z "$SRC" ]; then
            tar -xzf "$TMP/$FILE" -C "$TMP"
            SRC="$TMP/nocward-monitoring-agent-${VERSION}-linux-${ARCH}"
        fi
        [ -x "$SRC/nocward-agent" ] || die "the archive has no nocward-agent binary"
        systemctl stop nocward-agent >/dev/null 2>&1 || true
        install -m 0755 "$SRC/nocward-agent" /usr/bin/nocward-agent
        install -d -m 0755 /etc/nocward-agent /usr/lib/nocward-agent
        install -m 0644 "$SRC/agent.env.example" /etc/nocward-agent/agent.env.example
        install -m 0644 "$SRC/nocward-agent.service" /etc/systemd/system/nocward-agent.service
        install -m 0644 "$SRC/nocward-docker-proxy.service" /etc/systemd/system/nocward-docker-proxy.service
        : > /usr/lib/nocward-agent/installed-from-tar
        host_setup
        systemctl daemon-reload
        ;;
esac

# settings
if [ -n "$CA_FILE" ]; then
    [ -f "$CA_FILE" ] || die "--ca-file $CA_FILE not found"
    install -m 0644 "$CA_FILE" /etc/nocward-agent/ca.pem
    CA_FILE=/etc/nocward-agent/ca.pem
fi
set --
[ -n "$URL" ] && set -- "$@" --url "$URL"
[ -n "$KEY" ] && set -- "$@" --key "$KEY"
[ -n "$DEVICE" ] && set -- "$@" --device "$DEVICE"
[ -n "$PIN" ] && set -- "$@" --pin "$PIN"
[ -n "$CA_FILE" ] && set -- "$@" --ca-file "$CA_FILE"
[ -n "$PROXY" ] && set -- "$@" --proxy "$PROXY"
[ -n "$INTERVAL" ] && set -- "$@" --interval "$INTERVAL"
if [ $# -gt 0 ]; then
    /usr/bin/nocward-agent configure "$@" || die "the settings were refused (see above)"
fi

if grep -q '^NOCWARD_API_KEY=..*' /etc/nocward-agent/agent.env && grep -q '^NOCWARD_DEVICE_ID=..*' /etc/nocward-agent/agent.env; then
    systemctl enable nocward-agent >/dev/null 2>&1
    systemctl restart nocward-agent
    if /usr/bin/nocward-agent check; then
        say "installed $(/usr/bin/nocward-agent version) and running - the host appears on its device page within a minute"
    else
        say "installed and started, but the check above failed: fix the settings with 'nocward-agent configure ...', then 'systemctl restart nocward-agent'"
        exit 1
    fi
else
    say "installed $(/usr/bin/nocward-agent version). Connect it to the server:"
    say "  nocward-agent configure --url https://<server>/api --key <agent key> --device <device id>"
    say "  systemctl enable --now nocward-agent && nocward-agent check"
fi
