#!/usr/bin/env bash
# Run ON THE SERVER as the same user that runs kord (e.g. psa), after: ssh psa@server
# Switches kord user service from journal-only to append stdout/stderr under LOG_DIR/kord.log
# LOG_DIR is read from $KORD_HOME/.env (LOG_DIR=...) when present, else $KORD_HOME/logs.

set -euo pipefail

KORD_HOME="${KORD_HOME:-$HOME/kord}"
ENV_FILE="${KORD_ENV_FILE:-$KORD_HOME/.env}"
UNIT="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/kord.service"

# Last LOG_DIR= line from .env; strip quotes and ~ ; relative paths are under KORD_HOME
resolve_log_dir() {
  local default="${KORD_HOME}/logs" line raw
  [[ -f "$ENV_FILE" ]] || { echo "$default"; return; }
  line="$(grep -E '^[[:space:]]*LOG_DIR[[:space:]]*=' "$ENV_FILE" | tail -n1 || true)"
  [[ -z "$line" ]] && { echo "$default"; return; }
  raw="${line#*=}"
  raw="$(printf '%s' "$raw" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e $'s/\r$//')"
  if [[ "$raw" =~ ^\".*\"$ ]]; then raw="${raw#\"}"; raw="${raw%\"}"; fi
  if [[ "$raw" =~ ^\'.*\'$ ]]; then raw="${raw#\'}"; raw="${raw%\'}"; fi
  raw="${raw//\~/$HOME}"
  [[ -z "$raw" ]] && { echo "$default"; return; }
  if [[ "$raw" = /* ]]; then
    echo "$raw"
  else
    echo "${KORD_HOME}/${raw#./}"
  fi
}

LOG_DIR="$(resolve_log_dir)"
LOG_FILE="${LOG_DIR}/kord.log"

mkdir -p "$LOG_DIR"

if [[ ! -f "$UNIT" ]]; then
  echo "Unit not found: $UNIT" >&2
  exit 1
fi

cp -a "$UNIT" "${UNIT}.bak.$(date +%Y%m%d%H%M%S)"

# Point journal or any previous append paths at the log file derived from .env LOG_DIR
sed -i \
  -e "s|^StandardOutput=journal|StandardOutput=append:${LOG_FILE}|" \
  -e "s|^StandardError=journal|StandardError=append:${LOG_FILE}|" \
  "$UNIT"
sed -i \
  -e "s|^StandardOutput=append:.*|StandardOutput=append:${LOG_FILE}|" \
  -e "s|^StandardError=append:.*|StandardError=append:${LOG_FILE}|" \
  "$UNIT"

# systemd opens StandardOutput=append before ExecStart; missing parent dir → status 209/STDOUT
sed -i '/^ExecStartPre=-\/usr\/bin\/mkdir -p /d' "$UNIT"
tmp="$(mktemp)"
inserted=0
while IFS= read -r line || [[ -n "$line" ]]; do
  if [[ "$line" =~ ^ExecStart= ]] && [[ "$inserted" -eq 0 ]]; then
    printf '%s\n' "ExecStartPre=-/usr/bin/mkdir -p ${LOG_DIR}"
    inserted=1
  fi
  printf '%s\n' "$line"
done <"$UNIT" >"$tmp"
mv "$tmp" "$UNIT"

systemctl --user daemon-reload
systemctl --user restart kord

sleep 2
systemctl --user --no-pager status kord || true

echo "--- Last lines of $LOG_FILE (if any) ---"
if [[ -f "$LOG_FILE" ]]; then
  tail -n 20 "$LOG_FILE"
else
  echo "(file not created yet; check status above)"
fi

echo
echo "LOG_DIR=$LOG_DIR"
echo "Follow logs: tail -f $LOG_FILE"
