#!/bin/bash
# silvershell-agent role helper. Runs as root from silvershell-agent-role.service, started by
# silvershell-agent-role.path when the unprivileged agent writes a request file.
# Modelled on update-helper. It only ever runs scripts PACKAGED in $SSR_ROLES_DIR
# (/usr/lib/silvershell-agent/roles/<role>/<apply|status|remove>, root-owned) -- the request
# only names a role + action and supplies a params object; it never supplies code.
#
# SECURITY: role-result.json and role.log are world-readable (the agent user must read them).
# Role scripts must NEVER put secrets in their outputs (SSR_OUTPUTS) or print them to
# stdout/stderr. Public keys, addresses and ports are fine.
#
# Request  ($SSR_REQUEST): {"requestId":"<[A-Za-z0-9-]{1,64}>","role":"<[a-z0-9-]{1,40}>",
#                           "action":"apply|status|remove","params":{...}}
# Result   ($SSR_STATE_DIR/role-result.json):
#   {"requestId","role","action","outcome":"ok|failed|rejected","exitCode":n,"outputs":{},"error":"","at":"ISO8601"}
set -u

REQ="${SSR_REQUEST:-/run/silvershell-agent/role-request.json}"
STATE_DIR="${SSR_STATE_DIR:-/var/lib/silvershell-agent-role}"
ROLES_DIR="${SSR_ROLES_DIR:-/usr/lib/silvershell-agent/roles}"
TMPDIR_="${SSR_TMPDIR:-/tmp}"
TIMEOUT_SECONDS="${SSR_TIMEOUT_SECONDS:-1500}"
MAX_REQUEST_BYTES=65536
RESULT="$STATE_DIR/role-result.json"
LOG="$STATE_DIR/role.log"
REQUEST_ID="unknown"; ROLE=""; ACTION=""

log() { echo "silvershell-agent-role: $*"; }

# Installing the package replaces this file while it runs, so run from a private copy.
if [ "${SSR_REEXEC:-}" != "1" ]; then
  copy="$(mktemp "$TMPDIR_/ssr-role-helper.XXXXXX")" || exit 1
  cp "$0" "$copy" && chmod 0700 "$copy"
  SSR_REEXEC=1 exec bash "$copy" "$@"
fi
WORK=""
trap 'rm -f "$0"; [ -n "$WORK" ] && rm -rf "$WORK"' EXIT

command -v jq >/dev/null 2>&1 || { log "jq not installed"; exit 1; }
mkdir -p "$STATE_DIR"; chmod 0755 "$STATE_DIR" 2>/dev/null

write_result() { # outcome exitCode error [outputs-file]
  local tmp outputs='{}'
  [ -n "${4:-}" ] && [ -f "$4" ] && outputs="$(cat "$4")"
  tmp="$(mktemp "$STATE_DIR/.role-result.XXXXXX")" || { log "cannot create result file"; return 1; }
  jq -n --arg rid "$REQUEST_ID" --arg role "$ROLE" --arg action "$ACTION" --arg outcome "$1" \
        --argjson code "$2" --arg err "$(printf '%s' "$3" | LC_ALL=C tr -d '\000-\010\013-\037' | cut -c1-2000)" \
        --argjson outputs "$outputs" --arg at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
    '{requestId:$rid,role:$role,action:$action,outcome:$outcome,exitCode:$code,outputs:$outputs,error:$err,at:$at}' > "$tmp"
  chmod 0644 "$tmp"
  mv -fT "$tmp" "$RESULT"
  log "result: $1 ($ROLE/$ACTION, request $REQUEST_ID): $3"
}
reject() { # reason
  : > "$LOG"; chmod 0644 "$LOG"
  echo "== $REQUEST_ID $ROLE $ACTION $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$LOG"
  echo "rejected: $1" >> "$LOG"
  write_result rejected 0 "$1"; exit 0
}

# The agent controls this path: accept only a small regular file (no link, FIFO or directory).
if [ -L "$REQ" ] || { [ -e "$REQ" ] && [ ! -f "$REQ" ]; }; then
  rm -rf "$REQ"; reject "request is not a regular file"
fi
[ -f "$REQ" ] || { log "no request"; exit 0; }
WORK="$(mktemp -d "$TMPDIR_/ssr-work.XXXXXX")" || exit 1
chmod 0700 "$WORK"
SIZE="$(stat -c %s "$REQ" 2>/dev/null || echo 0)"
if [ "$SIZE" -gt "$MAX_REQUEST_BYTES" ]; then
  rm -f "$REQ"; reject "request larger than $MAX_REQUEST_BYTES bytes"
fi
timeout 5 head -c "$MAX_REQUEST_BYTES" "$REQ" > "$WORK/request.json"
rm -f "$REQ"

jq -e 'type=="object"' "$WORK/request.json" >/dev/null 2>&1 || reject "malformed request"
RID="$(jq -r '.requestId // "" | if type=="string" then . else "" end' "$WORK/request.json")"
if printf '%s' "$RID" | grep -Eq '^[A-Za-z0-9-]{1,64}$'; then REQUEST_ID="$RID"; else reject "malformed requestId"; fi
ROLE="$(jq -r '.role // "" | if type=="string" then . else "" end' "$WORK/request.json")"
ACTION="$(jq -r '.action // "" | if type=="string" then . else "" end' "$WORK/request.json")"
printf '%s' "$ROLE" | grep -Eq '^[a-z0-9-]{1,40}$' || { ROLE=""; reject "invalid role name"; }
case "$ACTION" in apply|status|remove) ;; *) ACTION=""; reject "invalid action";; esac
jq -e '(.params // {}) | type=="object"' "$WORK/request.json" >/dev/null 2>&1 || reject "params must be an object"
jq -c '.params // {}' "$WORK/request.json" > "$WORK/params.json"

SCRIPT="$ROLES_DIR/$ROLE/$ACTION"
if [ -L "$SCRIPT" ] || [ ! -f "$SCRIPT" ]; then reject "role '$ROLE' has no '$ACTION' script"; fi
if [ "${SSR_SKIP_OWNER_CHECK:-}" != "1" ]; then
  for p in "$SCRIPT" "$ROLES_DIR/$ROLE"; do
    read -r uid mode < <(stat -c '%u %a' "$p")
    if [ "$uid" != "0" ] || [ $(( 8#$mode & 8#022 )) -ne 0 ]; then reject "role script path is not root-owned or is writable by others"; fi
  done
fi
[ -x "$SCRIPT" ] || reject "role script is not executable"

: > "$LOG"; chmod 0644 "$LOG"
echo "== $REQUEST_ID $ROLE $ACTION $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$LOG"
OUTPUTS="$(mktemp "$STATE_DIR/.role-outputs.XXXXXX")" || exit 1
chmod 0600 "$OUTPUTS"; : > "$OUTPUTS"

log "running $ROLE/$ACTION (request $REQUEST_ID)"
( cd / && SSR_OUTPUTS="$OUTPUTS" SSR_REQUEST_ID="$REQUEST_ID" SSR_ROLE="$ROLE" SSR_ACTION="$ACTION" \
    PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" DEBIAN_FRONTEND=noninteractive \
    timeout "$TIMEOUT_SECONDS" "$SCRIPT" < "$WORK/params.json" >> "$LOG" 2>&1 )
RC=$?

OUT_FILE=""
if [ -s "$OUTPUTS" ] && [ "$(stat -c %s "$OUTPUTS")" -le "$MAX_REQUEST_BYTES" ] \
   && jq -ec 'select(type=="object")' "$OUTPUTS" > "$WORK/outputs.json" 2>/dev/null; then
  OUT_FILE="$WORK/outputs.json"
fi

if [ "$RC" -eq 0 ]; then
  write_result ok 0 "" "$OUT_FILE"
elif [ "$RC" -eq 124 ]; then
  write_result failed "$RC" "timed out after ${TIMEOUT_SECONDS}s" "$OUT_FILE"
else
  write_result failed "$RC" "role script exited with code $RC" "$OUT_FILE"
fi
rm -f "$OUTPUTS"
exit 0
