#!/usr/bin/env bash
#
# Finish setting up an installed DarkChan server: the identity key, the
# instances, the settings that need more than an editor, and the runbook for
# the parts no program can do for you.
#
# This is everything packaging/deploy-vps.sh does AFTER the build, for a host
# where the build already happened somewhere else — you installed the
# darkchan-server package. Both tools source packaging/deploy-lib.sh, so the
# instance naming, the identity-key handling and the closing runbook are the
# same code rather than the same intent written twice (§17).
#
#   sudo darkchan-server-setup --instances Family,Bypass
#   sudo darkchan-server-setup --identity-key ./old_server_identity.key \
#                              --replace-identity
#   sudo darkchan-server-setup --port 9000 --cert /etc/le/c.pem --key /etc/le/k.pem
#   sudo darkchan-server-setup                       # just print the runbook
#
set -euo pipefail

PROG=darkchan-server-setup
LIB=/usr/share/darkchan/deploy-lib.sh
[ -r "$LIB" ] || { echo "$PROG: $LIB is missing — reinstall darkchan-server" >&2
                   exit 1; }
# shellcheck source=packaging/deploy-lib.sh
. "$LIB"

CONF=/etc/default/darkchan-server
IDKEY=""
REPLACE_IDENTITY=0
INSTANCES=""
NEW_PORT=""
CERT=""
KEY=""

usage() {
  cat >&2 <<USAGE
usage: sudo $PROG [options]

  --instances A,B[,...]  name the instances: the first RENAMES the one the
                         server creates on its first boot, the rest are created
                         beside it. All closed (invite-only).
  --identity-key PATH    install PATH as the server identity key, so clients
                         that already pinned it keep their pin (CRYPTO.md §7.2)
  --replace-identity     allow replacing a key that is already there (the old
                         one is kept as server_identity.key.<epoch>.bak).
                         Installing the package starts the server, which
                         GENERATES a key immediately, so restoring an old one
                         onto a packaged install always needs this.
  --port N               set DARKCHAN_PORT in $CONF
  --cert PATH --key PATH set the certificate in DARKCHAN_EXTRA_ARGS there
  -h, --help             this

With no options it prints the runbook and changes nothing.
USAGE
}

while [ $# -gt 0 ]; do
  case "$1" in
    --instances)        INSTANCES="$2"; shift 2 ;;
    --identity-key)     IDKEY="$2"; shift 2 ;;
    --replace-identity) REPLACE_IDENTITY=1; shift ;;
    --port)             NEW_PORT="$2"; shift 2 ;;
    --cert)             CERT="$2"; shift 2 ;;
    --key)              KEY="$2"; shift 2 ;;
    -h|--help)          usage; exit 0 ;;
    *) err "unknown option '$1'"; usage; exit 2 ;;
  esac
done

[ "$(id -u)" = 0 ] || { err "run me as root (sudo $PROG ...)"; exit 1; }
if { [ -n "$CERT" ] && [ -z "$KEY" ]; } || { [ -z "$CERT" ] && [ -n "$KEY" ]; }
then
  err "--cert and --key go together"; exit 2
fi

# shellcheck source=/dev/null
[ -r "$CONF" ] && . "$CONF"
: "${DARKCHAN_DATA:=/var/lib/darkchan}"
: "${DARKCHAN_USER:=darkchan}"
: "${DARKCHAN_UNIT:=darkchan-server}"

# The library reads these names.
DATA_DIR="$DARKCHAN_DATA"
SVC_USER="$DARKCHAN_USER"
UNIT="$DARKCHAN_UNIT"
PORT="${NEW_PORT:-${DARKCHAN_PORT:-7420}}"

svc() { systemctl --system "$@" >/dev/null 2>&1 || true; }
svc_active() { systemctl --system is-active --quiet "$UNIT" 2>/dev/null; }
# svc_start_checked (deploy-lib.sh) is what puts it BACK: a plain start after a
# stop can be refused with start-limit-hit and leave the service down while
# this tool reports success.

# Set KEY=VALUE in the conffile: replace the line whether it is live or still
# commented out, and append if it is neither. Sed rather than an editor so this
# is idempotent and leaves the operator's other edits alone.
conf_set() { # <name> <value>
  local n="$1" v="$2"
  if grep -qE "^[[:space:]]*#?[[:space:]]*$n=" "$CONF" 2>/dev/null; then
    sed -i "s|^[[:space:]]*#\?[[:space:]]*$n=.*|$n=$v|" "$CONF"
  else
    printf '%s=%s\n' "$n" "$v" >> "$CONF"
  fi
  note "$CONF: $n=$v"
}

# ---- settings -------------------------------------------------------------
if [ -n "$NEW_PORT" ] || [ -n "$CERT" ]; then
  say "Settings"
  [ -f "$CONF" ] || { err "$CONF is missing — reinstall darkchan-server"; exit 1; }
  [ -n "$NEW_PORT" ] && conf_set DARKCHAN_PORT "$NEW_PORT"
  if [ -n "$CERT" ]; then
    for f in "$CERT" "$KEY"; do
      [ -f "$f" ] || { err "no such file: $f"; exit 1; }
    done
    conf_set DARKCHAN_EXTRA_ARGS "\"--cert $CERT --key $KEY\""
    # A certbot key is root-only again after EVERY renewal, not just today
    # (deploy-lib.sh explains why), so install the deploy hook that re-applies
    # the permissions rather than printing a recipe the operator retypes once.
    # It also applies them to the generation that is on disk now, which is why
    # the readability warning below covers what is left: a certificate from
    # somewhere other than certbot, and a hook that could not be written.
    install_certbot_hook "$KEY" || true
    if ! as_user "$SVC_USER" test -r "$KEY"; then
      note "WARNING: $SVC_USER cannot read $KEY — the server will not start."
      note "         chgrp $SVC_USER $KEY && chmod 0640 $KEY (certbot keys are"
      note "         root-only)"
    fi
  fi
  svc stop "$UNIT"
  svc_start_checked || exit 1
fi

# ---- the identity key -----------------------------------------------------
# Stop first: the server reads this file at startup, so replacing it underneath
# a running one changes nothing until the next restart — and leaves the running
# server presenting a key that is no longer on disk.
if [ -n "$IDKEY" ]; then
  was_active=0
  svc_active && was_active=1
  [ "$was_active" = 1 ] && svc stop "$UNIT"
  if ! install_identity_key; then
    # Put it back even though the operation failed — leaving the server down
    # because a flag was missing would be a far worse outcome than the refusal.
    [ "$was_active" = 1 ] && { svc_start_checked || true; }
    exit 1
  fi
  [ "$was_active" = 1 ] && { svc_start_checked || exit 1; }
fi

# ---- instances ------------------------------------------------------------
# The default instance exists only after a first boot, so make sure there has
# been one rather than telling the operator to come back later.
if [ -n "$INSTANCES" ]; then
  say "Instances"
  if ! [ -d "$DATA_DIR/instances" ]; then
    svc_active || svc_start_checked || exit 1
  fi
  if wait_for_instances 30; then
    inst_setup "$INSTANCES"
  else
    err "the server has not created its default instance — is it running?"
    note "systemctl status $UNIT ; journalctl -u $UNIT"
    exit 1
  fi
fi

# ---- what is left for a person --------------------------------------------
BACKUP_SH=/usr/share/darkchan/backup.sh
CERT_HINT="darkchan-server-setup --cert <fullchain.pem> --key <privkey.pem>"
UPDATE_HINT="   Update by installing a newer package: it keeps your settings in
   $CONF and your data in $DATA_DIR."
next_steps
