#!/usr/bin/env bash
# LogServer setup for Ubuntu 22.04 / 24.04 and Debian 12 / 13.
#
#   sudo bash LogServerSetup.sh                 install the latest version (or upgrade an existing install)
#   sudo bash LogServerSetup.sh --yes           the same, without questions
#   sudo bash LogServerSetup.sh --version 0.1.0 a specific version
#   sudo bash LogServerSetup.sh --package logserver-0.1.0.tar.gz    from a downloaded package (no internet for LogServer itself)
#   sudo bash LogServerSetup.sh --db-dir /data/postgresql           store the database there (otherwise you're asked)
#   sudo bash LogServerSetup.sh --uninstall [--purge]               remove LogServer (--purge also deletes its data)
#   sudo bash LogServerSetup.sh --force         carry on with this copy even though a newer installer is available
#
# Installs PostgreSQL, Python and the other prerequisites from the distribution's own repositories, the Python libraries
# LogServer uses from PyPI, and LogServer itself from the download site. Running it again upgrades LogServer and keeps
# its settings and data. Everything it does is logged to /var/log/logserver-setup.log.
set -euo pipefail

# Revision of this installer. Raise it whenever the installer itself changes: build_release.py publishes it as
# setup-version.txt, and an older copy of the installer stops and asks for the new one instead of upgrading.
SETUP_VERSION=4
BASE_URL="https://cdn.drf-solutions.net/software/Scripts/LogServer"
APP=/opt/logserver
ETC=/etc/logserver
DATA=/var/lib/logserver
CONFIG=$ETC/config.yaml
SVC_USER=logserver
DB_NAME=logserver
DB_USER=logserver
LOG=/var/log/logserver-setup.log

VERSION=""; PACKAGE=""; YES=""; UNINSTALL=""; PURGE=""; NO_FIREWALL=""; DB_DIR=""; FORCE=""
PG_DEFAULT=/var/lib/postgresql
TABLESPACE=logserver_data
usage() { sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; }
while [ $# -gt 0 ]; do
    case "$1" in
        --version) VERSION="${2:?}"; shift ;;
        --package) PACKAGE="${2:?}"; shift ;;
        --url) BASE_URL="${2:?}"; shift ;;
        --db-dir) DB_DIR="${2:?}"; shift ;;
        --yes|-y) YES=1 ;;
        --uninstall) UNINSTALL=1 ;;
        --purge) PURGE=1 ;;
        --no-firewall) NO_FIREWALL=1 ;;
        --force) FORCE=1 ;;
        -h|--help) usage 0 ;;
        *) echo "Unknown option: $1"; usage 1 ;;
    esac
    shift
done

# ------------------------------------------------------------------------------------------------ helpers
if [ -t 1 ]; then B=$'\e[1m'; G=$'\e[32m'; Y=$'\e[33m'; R=$'\e[31m'; N=$'\e[0m'; else B=""; G=""; Y=""; R=""; N=""; fi
step() { echo; echo "${B}==> $*${N}"; echo "==> $*" >> "$LOG"; }
info() { echo "    $*"; echo "    $*" >> "$LOG"; }
warn() { echo "${Y}    ! $*${N}"; echo "    ! $*" >> "$LOG"; }
die()  { echo "${R}ERROR: $*${N}" >&2; echo "ERROR: $*" >> "$LOG"; echo "    (details: $LOG)" >&2; exit 1; }
run()  { echo "+ $*" >> "$LOG"; "$@" >> "$LOG" 2>&1; }
ask() {   # ask "question" -> 0 for yes
    [ -n "$YES" ] && return 0
    local a
    if [ -r /dev/tty ]; then read -r -p "$1 [Y/n] " a < /dev/tty || a=n; else die "No terminal to ask on: run again with --yes"; fi
    case "${a:-y}" in [Yy]*) return 0 ;; *) return 1 ;; esac
}
randhex() { openssl rand -hex "$1"; }

[ "$(id -u)" -eq 0 ] || die "Run this as root, for example: sudo bash $0"
touch "$LOG"; chmod 600 "$LOG"
echo "---- $(date -Is) LogServerSetup $*" >> "$LOG"

# ------------------------------------------------------------------------------------------------ uninstall
if [ -n "$UNINSTALL" ]; then
    step "Removing LogServer"
    if [ -n "$PURGE" ]; then
        ask "This also DELETES the LogServer database, settings and all collected logs. Continue?" || exit 1
    else
        ask "Remove LogServer? (the database, settings and collected logs are kept)" || exit 1
    fi
    for u in logserver-collector logserver; do
        systemctl disable --now "$u" >> "$LOG" 2>&1 || true
        rm -f "/etc/systemd/system/$u.service"
    done
    systemctl daemon-reload
    rm -f /etc/sysctl.d/60-logserver.conf
    rm -rf "$APP"
    if [ -n "$PURGE" ]; then
        if command -v psql >/dev/null; then
            run sudo -u postgres dropdb --if-exists "$DB_NAME" || warn "Could not drop the database"
            run sudo -u postgres psql -c "drop tablespace if exists $TABLESPACE" || warn "Could not drop the LogServer tablespace"
            run sudo -u postgres psql -c "drop role if exists $DB_USER" || warn "Could not drop the database user"
            run sudo -u postgres psql -c "drop role if exists logserver_ai" || warn "Could not drop the AI Analytics database login"
        fi
        rm -rf "$ETC" "$DATA"
        userdel "$SVC_USER" >> "$LOG" 2>&1 || true
        info "LogServer, its database and all its data were removed. PostgreSQL itself is still installed."
    else
        info "LogServer was removed. Kept: the database '$DB_NAME', $ETC and $DATA (run again with --purge to delete them)."
    fi
    exit 0
fi

# ------------------------------------------------------------------------------------------------ checks
step "Checking this server"
[ -r /etc/os-release ] || die "Can't tell which Linux this is (no /etc/os-release)"
# read in a subshell: os-release defines VERSION, NAME, ... which must not replace this script's own variables
osr() { (. /etc/os-release && eval "echo \"\${$1:-}\""); }
OS_ID=$(osr ID); OS_VER=$(osr VERSION_ID); OS_NAME=$(osr NAME); OS_PRETTY=$(osr PRETTY_NAME)
case "$OS_ID:$OS_VER" in
    ubuntu:22.04|ubuntu:24.04|debian:12|debian:13) info "$OS_PRETTY - supported" ;;
    *) die "$OS_PRETTY isn't supported. Use Ubuntu 22.04 / 24.04 or Debian 12 / 13." ;;
esac
command -v systemctl >/dev/null && [ -d /run/systemd/system ] || die "systemd is required"
mem_mb=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo)
[ "$mem_mb" -ge 1800 ] || warn "Only ${mem_mb} MB of memory: 4 GB or more is recommended"
free_gb=$(df -BG --output=avail /var/lib 2>/dev/null | tail -1 | tr -dc 0-9)
[ "${free_gb:-0}" -ge 20 ] || warn "Only ${free_gb:-?} GB free under /var/lib (where the database and logs live): give it plenty of room"

UPGRADE=""
if [ -f "$CONFIG" ] && [ -d "$APP/server" ]; then
    UPGRADE=1
    OLD=$(grep -oP '__version__\s*=\s*"\K[^"]+' "$APP/server/logserver/__init__.py" 2>/dev/null || echo "unknown")
    info "LogServer $OLD is already installed: it will be upgraded, keeping its settings and data"
fi
if [ -n "$UPGRADE" ]; then ACTION=Upgrade; else ACTION=Install; fi
ask "$ACTION LogServer on this server?" || exit 1

# ------------------------------------------------------------------------------------------------ where the database goes
fs_of() {   # filesystem (device) holding a path, or its nearest existing parent
    local d="$1"; while [ ! -e "$d" ]; do d=$(dirname "$d"); done
    df -P "$d" | awk 'NR==2 {print $1}'
}
free_of() { local d="$1"; while [ ! -e "$d" ]; do d=$(dirname "$d"); done; df -h -P "$d" | awk 'NR==2 {print $4}'; }
if [ -z "$UPGRADE" ]; then
    if [ -z "$DB_DIR" ] && [ -z "$YES" ]; then
        step "Where should the database be stored?"
        info "The database holds every collected log, so it grows the most: put it on your largest disk."
        info "Mounted disks:"
        df -h -x tmpfs -x devtmpfs -x squashfs -x overlay -x efivarfs --output=target,size,avail,source 2>/dev/null \
            | sed 's/^/      /' | tee -a "$LOG"
        info "Press Enter for the default ($PG_DEFAULT), or type a folder on another disk (e.g. /data/postgresql)."
        [ -r /dev/tty ] || die "No terminal to ask on: run again with --yes (default location) or --db-dir PATH"
        read -r -p "    Database location [$PG_DEFAULT]: " DB_DIR < /dev/tty || true
    fi
    DB_DIR="${DB_DIR:-$PG_DEFAULT}"
    DB_DIR="${DB_DIR%/}"
    case "$DB_DIR" in
        /*) ;;
        *) die "The database location must be a full path starting with /" ;;
    esac
    [[ "$DB_DIR" =~ ^/[A-Za-z0-9._/-]+$ ]] || die "Use only letters, digits, . _ - and / in the database location"
    case "$DB_DIR/" in
        /|/bin/*|/boot/*|/dev/*|/etc/*|/lib*|/proc/*|/run/*|/sbin/*|/sys/*|/tmp/*|/usr/*|/opt/logserver/*|/var/lib/logserver/*|/root/*)
            die "$DB_DIR can't hold the database (a system or LogServer folder): choose a folder on a data disk" ;;
    esac
    if [ "$DB_DIR" = "$PG_DEFAULT" ]; then
        DB_DIR=""
        info "Database: PostgreSQL's default location ($PG_DEFAULT, $(free_of "$PG_DEFAULT") free)"
    else
        if [ -d "$DB_DIR" ] && [ -n "$(find "$DB_DIR" -mindepth 1 -maxdepth 1 ! -name lost+found -print -quit)" ]; then
            die "$DB_DIR already has files in it: choose an empty or new folder"
        fi
        info "Database: $DB_DIR (on $(fs_of "$DB_DIR"), $(free_of "$DB_DIR") free)"
        if [ "$(fs_of "$DB_DIR")" = "$(fs_of /)" ]; then
            warn "That folder is on the system disk, not a separate data disk"
        fi
        if [ -z "$YES" ]; then ask "Store the database in $DB_DIR?" || exit 1; fi
    fi
fi

# ------------------------------------------------------------------------------------------------ packages
step "Installing prerequisites from the $OS_NAME repositories (PostgreSQL, Python, ...)"
export DEBIAN_FRONTEND=noninteractive
run apt-get update || die "apt-get update failed"
run apt-get install -y --no-install-recommends postgresql python3 python3-venv curl ca-certificates openssl tar gzip iproute2 \
    || die "Installing packages failed"
run systemctl enable --now postgresql
pg=$(sudo -u postgres psql -tAc "show server_version" 2>/dev/null | cut -d' ' -f1)
info "PostgreSQL ${pg:-?}, $(python3 --version)"

# ------------------------------------------------------------------------------------------------ download
step "Getting LogServer"
WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT
if [ -n "$PACKAGE" ]; then
    [ -f "$PACKAGE" ] || die "Package not found: $PACKAGE"
    cp "$PACKAGE" "$WORK/pkg.tar.gz"
    if [ -f "$PACKAGE.sha256" ]; then
        (cd "$WORK" && awk '{print $1"  pkg.tar.gz"}' "$PACKAGE.sha256" | sha256sum -c --quiet) >> "$LOG" 2>&1 \
            || die "The package doesn't match its .sha256 file (damaged download?)"
        info "Package checksum OK"
    else
        warn "No $PACKAGE.sha256 next to the package: checksum not verified"
    fi
else
    fetch() { curl -fsSL --retry 3 --connect-timeout 15 -o "$2" "$1" >> "$LOG" 2>&1; }
    # Only reports a newer installer: it never downloads or runs one by itself.
    if fetch "$BASE_URL/setup-version.txt" "$WORK/setup-version.txt"; then
        LATEST_SETUP=$(tr -dc '0-9' < "$WORK/setup-version.txt")
        if [ -n "$LATEST_SETUP" ] && [ "$LATEST_SETUP" -gt "$SETUP_VERSION" ]; then
            if [ -n "$FORCE" ]; then
                warn "A newer installer is available (revision $LATEST_SETUP, this is $SETUP_VERSION): carrying on because of --force"
            else
                die "A newer installer is available (revision $LATEST_SETUP, this copy is $SETUP_VERSION). Nothing was changed.
       Download it and run that instead:  curl -fsSLO $BASE_URL/LogServerSetup.sh && sudo bash LogServerSetup.sh
       (or run this copy with --force)"
            fi
        fi
    else
        info "Couldn't check for a newer installer ($BASE_URL/setup-version.txt): carrying on"
    fi
    if [ -z "$VERSION" ]; then
        fetch "$BASE_URL/latest.txt" "$WORK/latest.txt" || die "Can't reach $BASE_URL/latest.txt"
        VERSION=$(tr -dc '0-9A-Za-z.\-' < "$WORK/latest.txt")
    fi
    [ -n "$VERSION" ] || die "Couldn't read the latest version from $BASE_URL/latest.txt"
    info "Downloading LogServer $VERSION"
    fetch "$BASE_URL/logserver-$VERSION.tar.gz" "$WORK/pkg.tar.gz" || die "Download failed: $BASE_URL/logserver-$VERSION.tar.gz"
    fetch "$BASE_URL/logserver-$VERSION.tar.gz.sha256" "$WORK/pkg.sha256" || die "Download failed: $BASE_URL/logserver-$VERSION.tar.gz.sha256"
    (cd "$WORK" && awk '{print $1"  pkg.tar.gz"}' pkg.sha256 | sha256sum -c --quiet) >> "$LOG" 2>&1 \
        || die "The download doesn't match its checksum (damaged or tampered with): nothing was changed"
    info "Checksum OK"
fi
mkdir "$WORK/x"
tar -xzf "$WORK/pkg.tar.gz" -C "$WORK/x" || die "The package couldn't be unpacked"
SRC=$(find "$WORK/x" -mindepth 1 -maxdepth 1 -type d | head -1)
[ -f "$SRC/server/logserver/__init__.py" ] && [ -d "$SRC/web" ] || die "This isn't a LogServer package"
NEW=$(grep -oP '__version__\s*=\s*"\K[^"]+' "$SRC/server/logserver/__init__.py")
info "LogServer $NEW"

# ------------------------------------------------------------------------------------------------ user, folders, code
step "Installing LogServer $NEW to $APP"
if ! id "$SVC_USER" >/dev/null 2>&1; then
    run useradd --system --home-dir "$DATA" --no-create-home --shell /usr/sbin/nologin "$SVC_USER"
    info "Created the service account '$SVC_USER'"
fi
install -d -o root -g root -m 755 "$APP"
install -d -o root -g "$SVC_USER" -m 770 "$ETC"
install -d -o "$SVC_USER" -g "$SVC_USER" -m 750 "$DATA"
install -d -o "$SVC_USER" -g "$SVC_USER" -m 750 "$DATA/geoip"
[ -n "$UPGRADE" ] && { systemctl stop logserver-collector logserver >> "$LOG" 2>&1 || true; }
for d in server web deploy; do
    rm -rf "$APP/$d.new"
    [ -d "$SRC/$d" ] && cp -a "$SRC/$d" "$APP/$d.new"
done
for d in server web deploy; do
    [ -d "$APP/$d.new" ] || continue
    rm -rf "$APP/$d.old"; [ -d "$APP/$d" ] && mv "$APP/$d" "$APP/$d.old"
    mv "$APP/$d.new" "$APP/$d"
done
rm -rf "$APP"/*.old
chown -R root:root "$APP/server" "$APP/web" "$APP/deploy" 2>/dev/null || true
chmod -R u=rwX,go=rX "$APP/server" "$APP/web" "$APP/deploy" 2>/dev/null || true

step "Installing the Python libraries (from PyPI)"
[ -x "$APP/venv/bin/python" ] || run python3 -m venv "$APP/venv" || die "Creating the Python environment failed"
run "$APP/venv/bin/pip" install --quiet --upgrade pip || die "Updating pip failed"
run "$APP/venv/bin/pip" install --quiet -r "$APP/server/requirements.txt" || die "Installing the Python libraries failed"
info "Done"

# ------------------------------------------------------------------------------------------------ database + config
if [ ! -f "$CONFIG" ]; then
    step "Creating the database"
    DB_PASS=$(randhex 24)
    if sudo -u postgres psql -tAc "select 1 from pg_roles where rolname='$DB_USER'" | grep -q 1; then
        sudo -u postgres psql -q -v ON_ERROR_STOP=1 -v pw="$DB_PASS" >> "$LOG" 2>&1 <<SQL || die "Couldn't reset the database user's password"
alter role $DB_USER with login password :'pw';
SQL
        info "Database user '$DB_USER' already existed: gave it a new password"
    else
        sudo -u postgres psql -q -v ON_ERROR_STOP=1 -v pw="$DB_PASS" >> "$LOG" 2>&1 <<SQL || die "Couldn't create the database user"
create role $DB_USER with login password :'pw';
SQL
    fi
    if sudo -u postgres psql -tAc "select 1 from pg_database where datname='$DB_NAME'" | grep -q 1; then
        info "Database '$DB_NAME' already existed: keeping it (where it is)"
    else
        TS_OPT=()
        if [ -n "$DB_DIR" ]; then
            others=$(sudo -u postgres psql -tAc "select count(*) from pg_database where datname not in ('postgres','template0','template1')")
            read -r PGVER PGCL PGDATA <<< "$(pg_lsclusters -h | awk 'NR==1 {print $1, $2, $6}')"
            if [ "$others" = "0" ] && [ "$(pg_lsclusters -h | wc -l)" = "1" ]; then
                # a brand-new PostgreSQL: recreate its (empty) cluster in the chosen folder, so all of it lives there
                info "Moving PostgreSQL $PGVER's data folder to $DB_DIR/$PGVER/$PGCL"
                install -d -o postgres -g postgres -m 755 "$DB_DIR"
                install -d -o postgres -g postgres -m 700 "$DB_DIR/$PGVER"
                run pg_dropcluster --stop "$PGVER" "$PGCL" || die "Couldn't stop and remove the empty PostgreSQL cluster"
                run pg_createcluster -d "$DB_DIR/$PGVER/$PGCL" -p 5432 "$PGVER" "$PGCL" || die "Couldn't create PostgreSQL's data folder in $DB_DIR"
                run systemctl restart postgresql
                run pg_ctlcluster "$PGVER" "$PGCL" start || true
                for _ in $(seq 1 30); do sudo -u postgres psql -tAc "select 1" >/dev/null 2>&1 && break; sleep 1; done
                [ "$(sudo -u postgres psql -tAc 'show data_directory')" = "$DB_DIR/$PGVER/$PGCL" ] \
                    || die "PostgreSQL didn't come back with its data in $DB_DIR"
                sudo -u postgres psql -q -v ON_ERROR_STOP=1 -v pw="$DB_PASS" >> "$LOG" 2>&1 <<SQL || die "Couldn't create the database user"
create role $DB_USER with login password :'pw';
SQL
            else
                # PostgreSQL already holds other databases: leave them, and put only LogServer's in the chosen folder
                info "PostgreSQL already has other databases: LogServer's will be stored in $DB_DIR (its own tablespace)"
                install -d -o postgres -g postgres -m 700 "$DB_DIR"
                sudo -u postgres psql -q -v ON_ERROR_STOP=1 -v loc="$DB_DIR" >> "$LOG" 2>&1 <<SQL || die "Couldn't create the tablespace in $DB_DIR"
create tablespace $TABLESPACE owner $DB_USER location :'loc';
SQL
                TS_OPT=(-D "$TABLESPACE")
            fi
        fi
        run sudo -u postgres createdb -O "$DB_USER" "${TS_OPT[@]}" "$DB_NAME" || die "Couldn't create the database"
        info "Created database '$DB_NAME'"
    fi
    umask 077
    cat > "$CONFIG" <<YAML
# LogServer start-up settings. Everything else is set in the web interface (Settings).
database:
  host: 127.0.0.1
  port: 5432
  name: $DB_NAME
  user: $DB_USER
  password: "$DB_PASS"
secret_key: "$(randhex 32)"
https:
  bind: 0.0.0.0
  port: 443
  http_redirect_port: 80
  cert_file: $DATA/certs/server.crt
  key_file: $DATA/certs/server.key
data_dir: $DATA
YAML
    umask 022
    info "Wrote $CONFIG (keep it safe: it holds the database password and the key that protects stored secrets)"
fi
chown root:"$SVC_USER" "$ETC" "$CONFIG"; chmod 770 "$ETC"; chmod 660 "$CONFIG"

# ------------------------------------------------------------------------------------------------ AI Analytics database login
# "Allow read-only database queries" (Settings > AI Analytics) runs the AI model's SQL as this separate login, which can
# only read the log views LogServer grants it. Creating a login needs PostgreSQL admin rights, so it's done here.
AI_DB=$ETC/ai-db.yaml
DB_HOST=$(awk '/^database:/ {f=1; next} f && /^[^ #]/ {f=0} f && $1 == "host:" {gsub(/"/, "", $2); print $2}' "$CONFIG")
if [ -z "$DB_HOST" ] || [ "$DB_HOST" = "127.0.0.1" ] || [ "$DB_HOST" = "localhost" ] || [ "$DB_HOST" = "::1" ]; then
    if [ ! -f "$AI_DB" ] || ! sudo -u postgres psql -tAc "select 1 from pg_roles where rolname='logserver_ai'" | grep -q 1; then
        step "Creating the read-only database login for AI Analytics"
        AI_PASS=$(randhex 24)
        sudo -u postgres psql -q -v ON_ERROR_STOP=1 -v pw="$AI_PASS" >> "$LOG" 2>&1 <<SQL || die "Couldn't create the read-only database login"
do \$\$ begin
    if not exists (select 1 from pg_roles where rolname = 'logserver_ai') then create role logserver_ai login; end if;
end \$\$;
alter role logserver_ai with login nosuperuser nocreatedb nocreaterole noinherit connection limit 5 password :'pw';
alter role logserver_ai set default_transaction_read_only = on;
SQL
        umask 077
        printf '# Read-only PostgreSQL login for AI Analytics database queries (created by LogServerSetup.sh)\nuser: logserver_ai\npassword: "%s"\n' "$AI_PASS" > "$AI_DB"
        umask 022
        info "Created login 'logserver_ai' (it can only read the log views LogServer gives it)"
    fi
    chown root:"$SVC_USER" "$AI_DB"; chmod 640 "$AI_DB"
else
    info "The database is on another server ($DB_HOST): to use read-only database queries in AI Analytics,"
    info "create the login there as described in Settings > AI Analytics."
fi

# ------------------------------------------------------------------------------------------------ services
step "Starting LogServer"
# Syslog arrives over UDP: let the collector keep a 32 MB receive buffer so bursts from several firewalls
# aren't dropped by the kernel (Linux allows only ~200 KB by default).
printf '%s\n' "# LogServer: room for bursts of syslog from several firewalls" "net.core.rmem_max = 33554432" \
    > /etc/sysctl.d/60-logserver.conf
run sysctl -q -p /etc/sysctl.d/60-logserver.conf || warn "Couldn't raise the UDP receive buffer limit (net.core.rmem_max)"
for u in logserver logserver-collector; do
    install -m 644 "$APP/deploy/$u.service" "/etc/systemd/system/$u.service"
done
systemctl daemon-reload
run systemctl enable logserver logserver-collector
run systemctl restart logserver
# Wait for the web interface. Upgrading a large database (many months of firewall events) can take a long time:
# keep waiting while the service is running and applying database updates, and say which one.
ok=""; since=$(date '+%Y-%m-%d %H:%M:%S'); waited=0; said=""
while [ "$waited" -lt 10800 ]; do
    if curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/api/public/appearance 2>/dev/null | grep -q 200; then ok=1; break; fi
    if ! systemctl is-active --quiet logserver && [ "$waited" -gt 20 ]; then break; fi
    mig=$(journalctl -u logserver --since "$since" --no-pager -o cat 2>/dev/null | grep -o 'Applying migration [0-9A-Za-z_.-]*' | tail -1 || true)
    if [ -z "$mig" ] && [ "$waited" -ge 120 ]; then break; fi
    if [ -n "$mig" ] && [ "$mig" != "$said" ]; then
        info "Updating the database: ${mig#Applying migration } (on a large database this can take several minutes - leave it running)"
        said=$mig
    fi
    sleep 2; waited=$((waited + 2))
done
if [ -z "$ok" ]; then
    journalctl -u logserver -n 30 --no-pager >> "$LOG" 2>&1 || true
    die "LogServer didn't start. See: journalctl -u logserver -n 50"
fi
run systemctl restart logserver-collector
sleep 3
systemctl is-active --quiet logserver-collector || warn "The collector service isn't running: journalctl -u logserver-collector -n 50"
info "Both services are running and start automatically"

# ------------------------------------------------------------------------------------------------ firewall
if [ -z "$NO_FIREWALL" ] && command -v ufw >/dev/null && ufw status 2>/dev/null | grep -q "Status: active"; then
    step "Opening the firewall (ufw) for the web interface"
    run ufw allow 443/tcp comment 'LogServer HTTPS'
    run ufw allow 80/tcp comment 'LogServer HTTP redirect'
    info "Allowed TCP 443 and 80"
fi

# ------------------------------------------------------------------------------------------------ done
IP=$(ip -4 route get 1.1.1.1 2>/dev/null | grep -oP 'src \K[0-9.]+' || true)
[ -n "$IP" ] || IP=$(hostname -I 2>/dev/null | awk '{print $1}')
FP=$(openssl x509 -in "$DATA/certs/server.crt" -noout -fingerprint -sha256 2>/dev/null | cut -d= -f2 || true)
echo
echo "${G}${B}LogServer $NEW is ${UPGRADE:+upgraded and }ready.${N}"
echo
echo "  Address:   ${B}https://$IP/${N}"
DBLOC=$(sudo -u postgres psql -tAc "select coalesce(nullif(pg_tablespace_location(dattablespace), ''), current_setting('data_directory'))
                                    from pg_database where datname='$DB_NAME'" 2>/dev/null | head -1)
[ -n "$(hostname -f 2>/dev/null)" ] && echo "             https://$(hostname -f)/"
[ -n "$DBLOC" ] && echo "  Database:  $DBLOC ($(free_of "$DBLOC") free)"
if [ -z "$UPGRADE" ]; then
    PWFILE="$DATA/initial-admin-password.txt"
    for _ in $(seq 1 20); do [ -f "$PWFILE" ] && break; sleep 0.5; done
    if [ -f "$PWFILE" ]; then
        echo "  Username:  ${B}admin${N}"
        echo "  Password:  ${B}$(grep -oP '^password: \K.*' "$PWFILE")${N}   (you choose a new one at first sign-in)"
        echo
        echo "  The password is also in $PWFILE - delete that file once you've signed in."
    else
        echo "  Sign in with an existing LogServer account (this database already had users)."
    fi
fi
echo
echo "  The browser will warn about the certificate: LogServer made its own (self-signed) one. Check it matches"
echo "  SHA-256 $FP"
echo "  and replace it with your own under Settings > SSL certificate."
echo
echo "  Next: Settings > Data sources to connect the firewall, Active Directory, Exchange, file servers, Microsoft 365 or UniFi."
if command -v ufw >/dev/null && ufw status 2>/dev/null | grep -q "Status: active"; then
    echo "  Firewall syslog: once set up, allow it from the firewall only, e.g.  ufw allow from <firewall IP> to any port 514 proto udp"
fi
echo "  Setup log: $LOG"
