#!/bin/sh
#
# Steid installer for a fresh Debian/Ubuntu server.
#
#     curl -fsSL https://releases.steid.dev/install.sh | sh -s -- --domain git.example.com
#
# It installs Steid to /opt/steid, keeps state in /var/lib/steid, runs it as an
# unprivileged system user under systemd, and puts Caddy in front of it with an
# automatic HTTPS certificate for the domain you give.
#
# Re-running it is an upgrade: it downloads the requested version, replaces the
# binary and assets, rewrites the unit and the Caddyfile, and restarts. It never
# touches /var/lib/steid, and it never overwrites /etc/steid/steid.env once that
# exists, so anything you have edited there survives.
#
# ON `curl | sh`: you are being asked to run a script you have not read, as root,
# from a URL. That is a real trust decision and "it's convenient" is not an
# answer to it. Two honest alternatives: download it first and read it
# (`curl -fsSL … -o install.sh; less install.sh; sh install.sh --domain …`), or
# follow the manual path in README.md, which is the same dozen commands written
# out. Nothing here is magic; the script exists to save typing, not to be trusted
# blindly.

set -eu

# --- WHERE RELEASES COME FROM -----------------------------------------------
#
# Since 0.6.0: **https://releases.steid.dev** — an S3 bucket behind CloudFront,
# run by the project. `jpgill.dev` serves the same files as a mirror and will
# keep doing so until the author's instance moves onto the managed fleet; see
# plans/decisions/0009-releases-from-releases-steid-dev.md for why the release
# host stopped being a Steid instance.
#
# The short version: from 0.4.0 the artefacts came off jpgill.dev, which is the
# author's live site *and* an instance of Steid. Serving Steid from Steid was the
# point. But the control plane now installs boxes headlessly from cloud-init, so
# every provision depends on that one instance being up, and an install that
# 404s reads as a broken product rather than a busy weekend. A dumb static host
# is the right dependency for a download; the demonstration was made and does not
# need making on every install.
#
# `--tarball` is still the bootstrap for the very first instance of a *new*
# distribution host, and the offline path.
#
# The layout expected here, and produced by release.sh, is unchanged from 0.4.0:
#
#     ${RELEASE_BASE_URL}/v${VERSION}/steid-${VERSION}-${TARGET}.tar.gz
#     ${RELEASE_BASE_URL}/v${VERSION}/steid-${VERSION}-${TARGET}.tar.gz.sha256
#
# so a link published against the old host still resolves against the mirror,
# and the two hosts differ only in their base.
#
# This is the *project's* distribution host — a constant, and NOT the `--domain`
# the person running this installs onto. Everyone downloads Steid from here; each
# installer then runs their own instance on their own hostname. Point
# STEID_RELEASE_BASE_URL at your own mirror to install from somewhere else; the
# path layout below is the whole contract.
#
# The version lives at the root of this host rather than under a repository path
# because the host is not an instance of Steid and has no /{handle} namespace to
# squat. On the mirror the old scoped path stays exactly as it was.
RELEASE_BASE_URL="${STEID_RELEASE_BASE_URL:-https://releases.steid.dev}"

# The version to install. Pinned rather than "latest" because there is no
# redirect to resolve "latest" against, and a pinned default makes the upgrade
# path explicit: `--version 0.7.0`.
VERSION="${STEID_VERSION:-0.7.0}"
# ----------------------------------------------------------------------------

# The build target to fetch. musl is preferred — one static binary that does not
# care which glibc the host has — but whether Steid builds against musl at all is
# still being established, so the choice is a variable rather than a fact.
# Override with --flavour gnu if the published artefacts are glibc.
# gnu, matching what release.sh builds. musl was tried and rejected: it fails on
# `ring` with Debian's musl-gcc wrapper, and — the decisive part — musl buys a
# binary with no runtime dependencies while Steid hard-requires `git` on PATH, so
# the portability cannot be used. THIS MUST AGREE WITH release.sh: they were
# briefly out of step and the symptom was a confusing "checksum mismatch",
# because the installer was looking for a musl tarball that was never built.
FLAVOUR="gnu"

DOMAIN=""
WWW=0
FORCE_CADDYFILE=0
# A local artefact to install instead of downloading one. This exists because of
# a bootstrap: the very first instance is what will *serve* the releases, so at
# that moment there is nowhere to download from. It doubles as the offline and
# air-gapped path.
TARBALL=""
PORT="3000"
# Scheduled backups are OFF unless asked for. A timer that appears without being
# asked for is a surprise, and this one writes a full copy of the instance to
# disk every night — which is exactly what somebody with a small volume needs to
# have agreed to. Omitting the flag on a later run leaves whatever is already
# installed alone, the way the Caddyfile and the env file are left alone;
# `--backups off` is how you actually remove it.
BACKUPS=""
# The owner to create at boot, written into steid.env. Both or neither: half of
# an owner is refused below rather than quietly installing an instance that comes
# up unclaimed, which is the state these exist to avoid.
OWNER_EMAIL=""
OWNER_HANDLE=""
# The organisation the instance is for, written into steid.env beside the owner.
# Optional, and only meaningful with an owner — an organisation with nobody to
# own it is not a state Steid has, so it is refused below rather than written.
# With it, the instance comes up as a company's Steid: the root lands on the
# organisation and the setup wizard has nothing left to ask.
OWNER_ORG=""
OWNER_ORG_NAME=""
# The operator surface's bearer token. Unlike everything else in steid.env this one
# IS rewritten on a later run when the flag is given — see the note above
# set_env_secret. Empty means "leave whatever is there alone", which is what an
# ordinary upgrade does.
OPERATOR_TOKEN=""
INSTALL_DIR="/opt/steid"
STATE_DIR="/var/lib/steid"
CONF_DIR="/etc/steid"
STEID_USER="steid"
INSTALL_CADDY=1

die() { echo "install.sh: $*" >&2; exit 1; }
say() { echo "==> $*"; }

# Sets one variable in steid.env, replacing the line if it is already there.
#
# **The one exception to "written once and left alone".** Every other setting in that
# file is written on the first install and never touched again, so an upgrade cannot
# revert something somebody deliberately changed. The operator token is different
# because it is not somebody's edit: it is a machine credential the thing that
# provisioned this box holds, it gets rotated, and a box that comes up with the
# operator surface off is a box a control plane cannot see. Only a run that passes the
# flag rewrites it; an upgrade without it leaves the line exactly where it was.
#
# **The value never reaches the terminal, a log or `ps`.** It is expanded into a
# here-doc inside this function and nowhere else; no `echo`, no `say`, no error
# message carries it. `set -x` is off — turning it on would print this like anything
# else, which is the ordinary hazard of tracing a script that handles a secret.
#
# The replacement is written beside the file under `umask 077` and moved into place,
# so the token is never briefly world-readable and an interrupted run cannot leave a
# truncated env file.
set_env_secret() {
    _key="$1"
    _value="$2"
    _file="${CONF_DIR}/steid.env"
    _tmp="${_file}.new"

    (umask 077; : > "$_tmp")

    if [ -f "$_file" ]; then
        # Both the line and the comment this function wrote above it, or a rotation
        # would stack a fresh comment on every run. `|| true`: grep exits 1 when it
        # prints nothing, which under `set -e` would end the install.
        grep -v -e "^${_key}=" -e "^# Written by install.sh --operator-token\.\$" \
            "$_file" >> "$_tmp" || true
    fi

    # `printf`, not a here-doc: a here-doc expands `$…` and backticks in the value, and
    # the value is a token somebody else generated. printf's %s takes it literally.
    printf '%s\n' "# Written by install.sh --operator-token." "${_key}=${_value}" >> "$_tmp"

    mv "$_tmp" "$_file"
    chmod 640 "$_file"
    chown "root:${STEID_USER}" "$_file"
}

usage() {
    cat >&2 <<'USAGE'
Usage: install.sh --domain <hostname> [options]

  --tarball <path>      install from a local tarball instead of downloading.
                        Needed for the first install, which has nowhere to
                        download from yet, and for offline installs.
  --www                 also serve www.<hostname>, redirecting it to the bare
                        hostname. Requires a www DNS record pointing here —
                        without one Caddy retries a certificate it cannot get.
  --force-caddyfile     overwrite an existing /etc/caddy/Caddyfile. Off by
                        default so an upgrade cannot silently discard your edits.
  --domain <hostname>   the public hostname, e.g. git.example.com. Its DNS must
                        already point at this machine or the certificate cannot
                        be issued. Required.
  --version <v>         release to install (default: the pinned one above)
  --flavour <musl|gnu>  which build to fetch (default: gnu — see below; musl
                        is not built, and asking for it gets a 404)
  --backups daily       install a systemd timer that runs `steid backup` into
                        /var/lib/steid/backups every night, keeps the most
                        recent 14, and tells the settings page when it last
                        ran. Off unless you ask. `--backups off` removes it.
                        These stay on the same machine — see the note at the
                        end for copying them somewhere else.
  --owner-email <addr>  create this owner at first boot, so the instance is
  --owner-handle <name> never unclaimed on the internet. Both or neither. The
                        owner gets no usable password: get in with
                        `steid reset-password <handle>` on this machine.
  --owner-org <handle>  also create this organisation at first boot, owned by
                        that owner, and land the root of the instance on it.
                        Needs the two flags above. Without it the root lands on
                        the owner's own page, which is what a one-person
                        instance wants.
  --owner-org-name <n>  the organisation's display name, e.g. "Acme Inc". Needs
                        --owner-org. Quote it if it has spaces.
  --operator-token <t>  bearer token for the operator surface (/metrics and the
                        detailed /api/instance). Written into steid.env before
                        Steid is started, so the instance never serves with that
                        surface off. This is the one setting a later run WILL
                        rewrite — pass it again to rotate the token; omit it and
                        the existing line is left alone like everything else.
                        Generate one with `openssl rand -hex 32`. It is never
                        printed.
  --port <n>            loopback port Steid listens on (default: 3000)
  --no-caddy            install and run Steid but do not touch Caddy. Only for
                        putting your own TLS-terminating proxy in front. Steid
                        has no TLS of its own; without a proxy, access tokens
                        cross the network in cleartext.
  -h, --help            this
USAGE
    exit "${1:-0}"
}

# --- arguments --------------------------------------------------------------

while [ $# -gt 0 ]; do
    case "$1" in
        --domain)  DOMAIN="${2:-}"; [ -n "$DOMAIN" ] || die "--domain needs a hostname"; shift 2 ;;
        --tarball) TARBALL="${2:-}"; [ -n "$TARBALL" ] || die "--tarball needs a path"; shift 2 ;;
        --www)     WWW=1; shift ;;
        --force-caddyfile) FORCE_CADDYFILE=1; shift ;;
        --version) VERSION="${2:-}"; [ -n "$VERSION" ] || die "--version needs a value"; shift 2 ;;
        --flavour) FLAVOUR="${2:-}"; [ -n "$FLAVOUR" ] || die "--flavour needs a value"; shift 2 ;;
        --port)    PORT="${2:-}"; [ -n "$PORT" ] || die "--port needs a number"; shift 2 ;;
        --owner-email)  OWNER_EMAIL="${2:-}"; [ -n "$OWNER_EMAIL" ] || die "--owner-email needs an address"; shift 2 ;;
        --owner-handle) OWNER_HANDLE="${2:-}"; [ -n "$OWNER_HANDLE" ] || die "--owner-handle needs a handle"; shift 2 ;;
        --owner-org)      OWNER_ORG="${2:-}"; [ -n "$OWNER_ORG" ] || die "--owner-org needs a handle"; shift 2 ;;
        --owner-org-name) OWNER_ORG_NAME="${2:-}"; [ -n "$OWNER_ORG_NAME" ] || die "--owner-org-name needs a name"; shift 2 ;;
        # Deliberately no value in the die message, here or anywhere below.
        --operator-token) OPERATOR_TOKEN="${2:-}"; [ -n "$OPERATOR_TOKEN" ] || die "--operator-token needs a value"; shift 2 ;;
        --backups) BACKUPS="${2:-}"; [ -n "$BACKUPS" ] || die "--backups needs daily or off"; shift 2 ;;
        --no-caddy) INSTALL_CADDY=0; shift ;;
        -h|--help) usage 0 ;;
        *) echo "install.sh: unknown argument: $1" >&2; usage 1 ;;
    esac
done

# Fail early and loudly rather than half-installing. Everything below this point
# assumes these hold.
[ "$(id -u)" = "0" ] || die "must run as root (try: sudo sh install.sh --domain …)"

if [ "$INSTALL_CADDY" = 1 ]; then
    [ -n "$DOMAIN" ] || die "--domain is required. Caddy needs a real hostname to
  obtain a certificate for, and Steid has no TLS of its own. If you are putting
  your own proxy in front, pass --no-caddy."
fi

if [ -n "$DOMAIN" ]; then
    case "$DOMAIN" in
        *[!A-Za-z0-9.-]*|-*|.*|*.) die "'$DOMAIN' does not look like a hostname" ;;
    esac
fi

case "$PORT" in
    ''|*[!0-9]*) die "--port must be a number" ;;
esac

case "$FLAVOUR" in
    musl|gnu) ;;
    *) die "--flavour must be 'musl' or 'gnu'" ;;
esac

case "$BACKUPS" in
    ''|daily|off) ;;
    *) die "--backups must be 'daily' or 'off'" ;;
esac

# Both or neither, and Steid itself refuses to start on half of them — so this is
# the same rule said at the moment it can still be fixed by retyping the command.
# Steid validates the values (the handle's shape, the reserved list, the email);
# this only checks that you gave both.
if [ -n "$OWNER_EMAIL" ] && [ -z "$OWNER_HANDLE" ]; then
    die "--owner-email needs --owner-handle too. Pass both or neither."
fi
if [ -n "$OWNER_HANDLE" ] && [ -z "$OWNER_EMAIL" ]; then
    die "--owner-handle needs --owner-email too. Pass both or neither."
fi

# An organisation with nobody to own it is not a state Steid has, so the same rule
# is said here rather than at the first boot that would have to refuse it. Steid
# validates the handle itself — the shape, and the reserved list.
if [ -n "$OWNER_ORG" ] && { [ -z "$OWNER_EMAIL" ] || [ -z "$OWNER_HANDLE" ]; }; then
    die "--owner-org needs --owner-email and --owner-handle too."
fi
if [ -n "$OWNER_ORG_NAME" ] && [ -z "$OWNER_ORG" ]; then
    die "--owner-org-name needs --owner-org too."
fi

# Where the timer writes, how many it keeps, and the file it touches afterwards.
# Steid reads only the marker's modification time, so this and the settings page
# cannot drift into disagreeing about a format.
BACKUP_DIR="${STATE_DIR}/backups"
BACKUP_KEEP=14
BACKUP_MARKER="${BACKUP_DIR}/.last-backup"

case "${TARBALL:+local}${RELEASE_BASE_URL}" in
    local*) : ;;  # installing from a file; the download URL is irrelevant
    *REPLACE-ME*) die "RELEASE_BASE_URL is still the placeholder. Edit the top of
  this script (or set STEID_RELEASE_BASE_URL) to point at real release artefacts,
  or pass --tarball to install from a local file." ;;
esac

command -v systemctl >/dev/null 2>&1 || die "no systemd here; follow the manual path in README.md"
command -v apt-get >/dev/null 2>&1 || die "this installer only knows apt (Debian/Ubuntu).
  The manual path in README.md works on anything with systemd."

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

TARGET="${ARCH}-unknown-linux-${FLAVOUR}"
NAME="steid-${VERSION}-${TARGET}"
URL="${RELEASE_BASE_URL}/v${VERSION}/${NAME}.tar.gz"

say "installing Steid ${VERSION} (${TARGET}) for ${DOMAIN:-<no domain>}"

# --- prerequisites ----------------------------------------------------------

# git is not optional and not a runtime nicety: Steid shells out to `git init
# --bare` to create a repository and to `git http-backend` to serve every clone
# and push. Without it the install succeeds and the first repository fails.
say "installing prerequisites (git, curl, ca-certificates)"
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq --no-install-recommends git curl ca-certificates

# --- download ---------------------------------------------------------------

TMP="$(mktemp -d)"
# shellcheck disable=SC2064  # $TMP is expanded now on purpose: it never changes.
trap "rm -rf '$TMP'" EXIT INT TERM

if [ -n "$TARBALL" ]; then
    [ -f "$TARBALL" ] || die "--tarball: no such file: ${TARBALL}"
    say "installing from ${TARBALL}"
    cp "$TARBALL" "${TMP}/${NAME}.tar.gz"

    # A checksum beside a local file is verified when present, but not demanded:
    # whoever passes --tarball already chose the bytes, so refusing to proceed
    # without a .sha256 would block the bootstrap this option exists for.
    if [ -f "${TARBALL}.sha256" ]; then
        say "verifying checksum"
        # Compared by value, not with `sha256sum -c`: that matches on the filename
        # recorded inside the .sha256, which need not be what the file is called
        # by the time someone passes it here.
        EXPECTED="$(cut -d" " -f1 < "${TARBALL}.sha256")"
        ACTUAL="$(sha256sum < "${TMP}/${NAME}.tar.gz" | cut -d" " -f1)"
        [ "$EXPECTED" = "$ACTUAL" ] \
            || die "checksum mismatch — ${TARBALL} does not match its .sha256"
    else
        say "no ${TARBALL}.sha256 beside it; installing unverified"
    fi
else
    say "downloading ${URL}"
    curl -fsSL "$URL" -o "${TMP}/${NAME}.tar.gz" \
        || die "download failed. Is version ${VERSION} published for ${TARGET}?"
    curl -fsSL "${URL}.sha256" -o "${TMP}/${NAME}.tar.gz.sha256" \
        || die "checksum file missing next to the tarball; refusing to install unverified"

    say "verifying checksum"
    ( cd "$TMP" && sha256sum -c "${NAME}.tar.gz.sha256" >/dev/null ) \
        || die "checksum mismatch — the download is corrupt or tampered with"
fi

tar -xzf "${TMP}/${NAME}.tar.gz" -C "$TMP"
[ -x "${TMP}/${NAME}/steid" ] || die "tarball has no steid binary at ${NAME}/steid"
# The bundle must ship and must land beside the binary: AssetBundle::load() walks
# up from the executable looking for assets/manifest.toml and the process exits
# at startup without it.
[ -f "${TMP}/${NAME}/assets/manifest.toml" ] || die "tarball has no assets/manifest.toml"

# --- user and directories ---------------------------------------------------

if ! id "$STEID_USER" >/dev/null 2>&1; then
    say "creating system user ${STEID_USER}"
    # --home is the state directory: git wants a HOME, and giving it the one
    # directory the service can write keeps that from being a surprise later.
    useradd --system --home-dir "$STATE_DIR" --shell /usr/sbin/nologin "$STEID_USER"
fi

mkdir -p "$INSTALL_DIR" "$STATE_DIR" "$CONF_DIR"
# State is exactly two things: the SQLite database file and the repository
# directory. Both live here, and together they are the entire backup surface.
mkdir -p "${STATE_DIR}/repos"
chown -R "${STEID_USER}:${STEID_USER}" "$STATE_DIR"
chmod 750 "$STATE_DIR"

# --- install files ----------------------------------------------------------

# Stop before replacing the binary: overwriting a running executable in place
# fails with ETXTBSY, and a half-swapped install/assets pair would serve stale
# hashed CSS until the next restart anyway.
if systemctl is-active --quiet steid 2>/dev/null; then
    say "stopping steid for the upgrade"
    systemctl stop steid
fi

say "installing to ${INSTALL_DIR}"
install -m 0755 "${TMP}/${NAME}/steid" "${INSTALL_DIR}/steid"
rm -rf "${INSTALL_DIR}/assets"
cp -R "${TMP}/${NAME}/assets" "${INSTALL_DIR}/assets"
if [ -f "${TMP}/${NAME}/README.md" ]; then
    cp "${TMP}/${NAME}/README.md" "${INSTALL_DIR}/README.md"
fi
chown -R root:root "$INSTALL_DIR"
# Read-only to the service user on purpose: Steid never writes here.
chmod -R a+rX "$INSTALL_DIR"

# --- configuration ----------------------------------------------------------

# Written once and then left alone, so an upgrade cannot silently revert a
# setting someone deliberately changed.
# Whether this run wrote the env file, which is also whether the owner flags did
# anything: they are only ever written on the first write, like every other
# setting here.
ENV_WRITTEN=0
if [ ! -f "${CONF_DIR}/steid.env" ]; then
    ENV_WRITTEN=1
    say "writing ${CONF_DIR}/steid.env"
    cat > "${CONF_DIR}/steid.env" <<EOF
# Steid configuration. Restart after editing: systemctl restart steid

# All state lives under ${STATE_DIR}. SQLite writes -wal and -shm siblings, so
# the directory must be writable, not just the file.
STEID_DATABASE_URL=sqlite:${STATE_DIR}/steid.db?mode=rwc
STEID_DATA_DIR=${STATE_DIR}/repos

# HOST and PORT are read by the web framework itself and are deliberately not
# STEID_-prefixed. Loopback only: Caddy is the way in, and binding 0.0.0.0 would
# expose plain HTTP — and therefore access tokens in cleartext — to the internet.
HOST=127.0.0.1
PORT=${PORT}

# Caddy sits in front and appends the address it accepted the connection from to
# X-Forwarded-For, so the rate limiters may trust that header to tell one caller
# from another. Turn this OFF if you ever put Steid on a public port directly:
# with nothing appending the header a caller can invent one per request and buy
# itself a fresh rate-limit budget each time.
STEID_TRUSTED_PROXY=true

# The address this instance answers on, used by \`steid reset-password\` to print a
# whole link. Every link built while serving is derived from the request instead,
# so this is read by the command line and nothing else.
STEID_PUBLIC_URL=https://${DOMAIN}

# Outgoing mail, for password reset. Both are needed or neither does anything:
# without them the forgot-password page says so and points at
# \`steid reset-password <handle>\`, which prints a one-time link on this machine.
# The URL carries the submission password, which is why this file is mode 640. Quote
# any value containing spaces or angle brackets.
#   STEID_SMTP_URL=smtps://user:password@smtp.example.com:465
#   STEID_MAIL_FROM="Steid <steid@${DOMAIN}>"

# Deliberately absent: STEID_INSECURE_COOKIES. It strips Secure from the session
# cookie and exists only for plain-HTTP local development. Setting it here would
# hand out a session cookie that any network hop can read.
EOF

    # Only when asked for, and only here — inside the "first write" branch, like
    # everything else in this file. An upgrade must not re-seed anything, and in
    # any case Steid ignores these the moment an owner exists.
    if [ -n "$OWNER_EMAIL" ]; then
        cat >> "${CONF_DIR}/steid.env" <<EOF

# The owner, created on the first boot that finds this instance unclaimed. Read
# together — Steid refuses to start with one of them set and not the other — and
# inert from the moment an owner exists, so they can stay here for the life of
# the instance. This is what makes an unattended install come up already claimed
# rather than serving a setup page to whoever finds it first.
#
# The owner created this way has NO usable password. The way in is
#     ${INSTALL_DIR}/steid reset-password ${OWNER_HANDLE}
# run on this machine, which prints a one-time link.
STEID_OWNER_EMAIL=${OWNER_EMAIL}
STEID_OWNER_HANDLE=${OWNER_HANDLE}
EOF
        # Beside the owner, in the same first-write branch and inert for the same
        # reason: once an owner exists Steid reads none of these again. The display
        # name is quoted because it may contain spaces.
        if [ -n "$OWNER_ORG" ]; then
            cat >> "${CONF_DIR}/steid.env" <<EOF
# The organisation this instance is for, created at the same first boot and set
# as the home page — so the root lands on it rather than on the owner's own
# page. Inert once an owner exists, like the two above.
STEID_OWNER_ORG=${OWNER_ORG}
EOF
            if [ -n "$OWNER_ORG_NAME" ]; then
                cat >> "${CONF_DIR}/steid.env" <<EOF
STEID_OWNER_ORG_NAME="${OWNER_ORG_NAME}"
EOF
            fi
        fi
    fi
    chmod 640 "${CONF_DIR}/steid.env"
    chown "root:${STEID_USER}" "${CONF_DIR}/steid.env"
else
    say "keeping existing ${CONF_DIR}/steid.env"
    if [ -n "$OWNER_EMAIL" ]; then
        say "--owner-email/--owner-handle/--owner-org ignored: ${CONF_DIR}/steid.env already exists"
    fi
fi

# After the branch, so it applies to a first install and to a later run alike — and
# before the unit is written and Steid is restarted, which is the whole point: the
# instance must never serve with the operator surface off waiting for something to
# come along afterwards and set this. The key is named; the value is not.
if [ -n "$OPERATOR_TOKEN" ]; then
    say "setting STEID_OPERATOR_TOKEN in ${CONF_DIR}/steid.env"
    set_env_secret STEID_OPERATOR_TOKEN "$OPERATOR_TOKEN"
fi

say "writing /etc/systemd/system/steid.service"
cat > /etc/systemd/system/steid.service <<EOF
# Managed by install.sh. Re-running the installer rewrites this file.
[Unit]
Description=Steid
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=${STEID_USER}
Group=${STEID_USER}
WorkingDirectory=${INSTALL_DIR}
ExecStart=${INSTALL_DIR}/steid
EnvironmentFile=${CONF_DIR}/steid.env
Environment=HOME=${STATE_DIR}
Restart=on-failure
RestartSec=2s

NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectSystem=strict
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictSUIDSGID=true
RestrictNamespaces=true
LockPersonality=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
ReadWritePaths=${STATE_DIR}

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --quiet steid
say "starting steid"
systemctl restart steid

# --- scheduled backups ------------------------------------------------------

if [ "$BACKUPS" = "daily" ]; then
    say "installing the nightly backup timer"

    mkdir -p "$BACKUP_DIR"
    chown "${STEID_USER}:${STEID_USER}" "$BACKUP_DIR"
    # 700: an archive here is every row and every private repository in one file.
    chmod 700 "$BACKUP_DIR"

    # The env file is never rewritten, so the marker is appended rather than
    # written with the rest — and only once, so re-running is idempotent.
    if ! grep -q '^STEID_BACKUP_MARKER=' "${CONF_DIR}/steid.env"; then
        cat >> "${CONF_DIR}/steid.env" <<EOF

# Added by install.sh --backups daily. Steid reads this file's modification
# time to show the last automatic backup on the settings page, and nothing else
# about it. Removing the line makes the page say "none configured".
STEID_BACKUP_MARKER=${BACKUP_MARKER}
EOF
    fi

    cat > /etc/systemd/system/steid-backup.service <<EOF
# Managed by install.sh --backups daily.
[Unit]
Description=Steid backup
# The backup is taken through SQLite's own VACUUM INTO, so it is consistent with
# the service running — this deliberately does not stop Steid.
After=steid.service

[Service]
Type=oneshot
User=${STEID_USER}
Group=${STEID_USER}
WorkingDirectory=${INSTALL_DIR}
EnvironmentFile=${CONF_DIR}/steid.env
Environment=HOME=${STATE_DIR}
ExecStart=${INSTALL_DIR}/steid backup ${BACKUP_DIR}
# Pruning and the marker run only if the backup succeeded, which is the point of
# ExecStartPost: a failed run must not look like a successful one on the page.
# The \`;\` before touch is deliberate — an empty glob must not fail the unit.
ExecStartPost=/bin/sh -c 'cd ${BACKUP_DIR} && ls -1t steid-*.tar.gz 2>/dev/null | tail -n +$((BACKUP_KEEP + 1)) | xargs -r rm -f; touch ${BACKUP_MARKER}'

NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectSystem=strict
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictSUIDSGID=true
RestrictNamespaces=true
LockPersonality=true
RestrictAddressFamilies=AF_UNIX
ReadWritePaths=${STATE_DIR}
EOF

    cat > /etc/systemd/system/steid-backup.timer <<'EOF'
# Managed by install.sh --backups daily.
[Unit]
Description=Nightly Steid backup

[Timer]
OnCalendar=daily
# Spread across the hour so a fleet of instances does not all gzip themselves at
# once, and catch up after a reboot rather than skipping the night.
RandomizedDelaySec=1h
Persistent=true

[Install]
WantedBy=timers.target
EOF

    systemctl daemon-reload
    systemctl enable --quiet --now steid-backup.timer
elif [ "$BACKUPS" = "off" ]; then
    if [ -f /etc/systemd/system/steid-backup.timer ]; then
        say "removing the backup timer (archives in ${BACKUP_DIR} are left alone)"
        systemctl disable --quiet --now steid-backup.timer 2>/dev/null || true
        rm -f /etc/systemd/system/steid-backup.timer /etc/systemd/system/steid-backup.service
        systemctl daemon-reload
    fi
fi

# --- caddy ------------------------------------------------------------------

if [ "$INSTALL_CADDY" = 1 ]; then
    # Whether Caddy was here *before* this run decides whether /etc/caddy/Caddyfile
    # is somebody's configuration or the one the .deb ships. It has to be sampled
    # here, because thirty lines later the package has been installed either way.
    CADDY_WAS_INSTALLED=1
    if ! command -v caddy >/dev/null 2>&1; then
        CADDY_WAS_INSTALLED=0
        say "installing Caddy from its official apt repository"
        apt-get install -y -qq --no-install-recommends debian-keyring debian-archive-keyring apt-transport-https gnupg
        curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
            | gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
        curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
            > /etc/apt/sources.list.d/caddy-stable.list
        apt-get update -qq
        apt-get install -y -qq caddy
    else
        say "Caddy already installed"
    fi

    # NOT rewritten on upgrade. This used to be overwritten every run, which
    # silently discarded operator edits — a www redirect added by hand vanished on
    # the next install and took the site's www hostname with it, with nothing in the
    # output to say so. The env file was already treated this way; the two now agree.
    #
    # CADDY_WAS_INSTALLED is the whole point of the second condition. The Caddy
    # package ships its own /etc/caddy/Caddyfile — a placeholder site on :80 — so
    # on a first install the file always exists by the time we look, and "keep
    # what is there" quietly meant "keep the placeholder". The stranger's install
    # then succeeded, Steid ran, and the domain served Caddy's welcome page with
    # nothing anywhere saying why. Found in a container running the published
    # one-liner, which is the only way it shows up: an upgrade never hits it.
    if [ -f /etc/caddy/Caddyfile ] && [ "$FORCE_CADDYFILE" = 0 ] && [ "$CADDY_WAS_INSTALLED" = 1 ]; then
        say "keeping existing /etc/caddy/Caddyfile (--force-caddyfile to replace)"
        # And say so when that file cannot possibly be serving Steid, rather than
        # leaving the operator to find out from a browser.
        if ! grep -q "127.0.0.1:${PORT}" /etc/caddy/Caddyfile; then
            echo "install.sh: WARNING — /etc/caddy/Caddyfile does not proxy 127.0.0.1:${PORT}," >&2
            echo "  so ${DOMAIN} will not reach Steid. Add a reverse_proxy to it (see" >&2
            echo "  deploy/Caddyfile in the source tree), or re-run with --force-caddyfile" >&2
            echo "  to have this installer write a fresh one." >&2
        fi
    else
        say "writing /etc/caddy/Caddyfile for ${DOMAIN}"
        mkdir -p /etc/caddy

        WWW_BLOCK=""
        if [ "$WWW" = 1 ]; then
            WWW_BLOCK="
# www redirects to the bare hostname so there is one canonical URL.
www.${DOMAIN} {
	redir https://${DOMAIN}{uri} permanent
}"
        fi

        cat > /etc/caddy/Caddyfile <<EOF
# Written by install.sh on first install only. Later runs leave it alone, so edits
# here survive an upgrade. Use --force-caddyfile to have the installer replace it.
#
# Steid has no TLS of its own (Topcoat 0.5 ships none), and it authenticates git
# over HTTP Basic — so without this proxy every push would send a personal access
# token in cleartext. Caddy obtains and renews the certificate automatically,
# provided ${DOMAIN} resolves here and ports 80 and 443 are open.
${DOMAIN} {
	reverse_proxy 127.0.0.1:${PORT} {
		# Git's smart HTTP is a streaming protocol in both directions; buffering
		# it turns a clone into a long silence and can stall negotiation.
		flush_interval -1
	}
}
${WWW_BLOCK}
EOF
    fi

    systemctl enable --quiet caddy
    systemctl reload caddy 2>/dev/null || systemctl restart caddy
fi

# --- report -----------------------------------------------------------------

# A moment for the service to either come up or fall over, so the message below
# reflects reality rather than optimism.
sleep 2
if ! systemctl is-active --quiet steid; then
    echo >&2
    echo "install.sh: steid is installed but not running. Look at:" >&2
    echo "    journalctl -u steid -n 50 --no-pager" >&2
    exit 1
fi

if [ "$INSTALL_CADDY" = 1 ]; then
    BASE_URL="https://${DOMAIN}"
else
    BASE_URL="http://127.0.0.1:${PORT}  (put your own TLS proxy in front of this)"
fi

# Said only when a timer was installed, and said with the offsite caveat
# attached: a nightly archive that never leaves the machine survives a mistake
# and does not survive the machine.
if [ -f /etc/systemd/system/steid-backup.timer ]; then
    BACKUP_REPORT="  Backups     nightly into ${BACKUP_DIR}, keeping ${BACKUP_KEEP}
              systemctl list-timers steid-backup.timer
              Take one now: ${INSTALL_DIR}/steid backup ${BACKUP_DIR}

  !! These sit on this machine's disk. Copy them somewhere else — any
  !! rclone remote will do, as a second timer or from your laptop:
  !!     rclone sync ${BACKUP_DIR} remote:steid-backups
"
else
    BACKUP_REPORT="  Backups     none scheduled. Re-run with --backups daily, or take one by
              hand: ${INSTALL_DIR}/steid backup /var/backups
"
fi

# Two different next steps, because a seeded instance has no token and no setup
# page: it is already owned, and what its owner needs is a way in rather than a
# way to claim.
if [ -n "$OWNER_EMAIL" ] && [ "$ENV_WRITTEN" = 1 ]; then
    CLAIM_REPORT="This instance is already claimed: ${OWNER_HANDLE} <${OWNER_EMAIL}> was created
at first boot, so there was never a moment when a stranger could claim it.${OWNER_ORG:+
It is owned by the organisation ${OWNER_ORG}, which the root lands on.}

  That owner has no password. Mint a one-time sign-in link on this machine:

      ${INSTALL_DIR}/steid reset-password ${OWNER_HANDLE}

  It works once and expires in 30 minutes, and it is as good as the password —
  hand it over the way you would one.
"
else
    CLAIM_REPORT="Next: claim the instance.

  The setup token is printed to the log at startup, and ONLY while the instance
  is unclaimed. It is held in memory, so every restart mints a new one:

      journalctl -u steid --no-pager | tail -n 30

  Then open ${BASE_URL}/auth/setup and paste it in.
"
fi

cat <<EOF

Steid ${VERSION} is running.

  Service     systemctl status steid
  Logs        journalctl -u steid -f
  Config      ${CONF_DIR}/steid.env
  State       ${STATE_DIR}   (the database and the repos — back up this directory)
${BACKUP_REPORT}
${CLAIM_REPORT}
To upgrade later, re-run this script with a newer --version. It replaces the
binary and assets and leaves ${STATE_DIR} untouched.
EOF
