#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Service-user enrollment and explicit paired Docker deployment operations.
set -euo pipefail
export PATH=/usr/sbin:/usr/bin:/sbin:/bin

die() {
  printf 'DEM browser runtime: %s\n' "$*" >&2
  exit 1
}

[[ $# -ge 1 ]] || die 'expected one Docker runtime operation'
action=$1
shift
case "$action" in
  identity | plan | ensure | pair-plan | fetch | prepare | activate | rollback | status) ;;
  *) die 'invalid Docker runtime operation' ;;
esac
case "$action" in
  fetch | prepare | rollback) ;;
  *) [[ $# == 0 ]] || die 'this Docker runtime operation accepts no flags' ;;
esac

arguments=()
seen=' '
output= release= archive= keyring=
allow_download=no
[[ $# -le 9 ]] || die 'too many Docker runtime arguments'
while [[ $# -gt 0 ]]; do
  flag=$1
  [[ $seen != *" $flag "* ]] || die 'duplicate Docker runtime flag'
  seen+="$flag "
  case "$action:$flag" in
    fetch:--allow-download | rollback:--prepared-only)
      [[ $flag != --allow-download ]] || allow_download=yes
      arguments+=("$flag")
      shift ;;
    fetch:--output | fetch:--release | fetch:--archive | fetch:--keyring | \
    prepare:--release | prepare:--archive | prepare:--keyring)
      [[ $# -ge 2 ]] || die 'Docker runtime flag requires an absolute path'
      value=$2
      [[ $value == /* && ${#value} -le 4096 && ! $value =~ [[:cntrl:]] ]] ||
        die 'Docker runtime paths must be absolute, bounded and free of control bytes'
      case "$flag" in
        --output) output=$value ;;
        --release) release=$value ;;
        --archive) archive=$value ;;
        --keyring) keyring=$value ;;
      esac
      arguments+=("$flag" "$value")
      shift 2 ;;
    *) die 'unsupported Docker runtime flag; use the paired deployment owner to stop consumers and replace the pinned image' ;;
  esac
done
if [[ $action == fetch ]]; then
  [[ -n $output ]] || die 'fetch requires --output outside the managed runtime root'
  if [[ $allow_download == yes ]]; then
    [[ -z $archive && -z $keyring ]] || die 'online fetch cannot use offline archive or keyring flags'
  else
    [[ -n $release && -n $archive ]] || die 'fetch requires explicit --allow-download or signed offline release and archive paths'
  fi
elif [[ $action == prepare ]]; then
  [[ -n $release && -n $archive ]] || die 'prepare is offline; fetch authenticated inputs before stopping the old deployment'
fi

# Kickstart verifies that the container runs the stock Agent invocation.
service_user=${DOCKER_USR:-netdata}
service_uid=$(id -u -- "$service_user")
service_gid=$(id -g -- "$service_user")
[[ $service_uid =~ ^[1-9][0-9]*$ && $service_gid =~ ^[1-9][0-9]*$ ]] ||
  die 'Docker enrollment requires a service account with a nonzero UID and GID'

if [[ $action == identity ]]; then
  printf '%s:%s\n' "$service_uid" "$service_gid"
  exit 0
fi
[[ $EUID == "$service_uid" && $(id -g) == "$service_gid" ]] ||
  die 'invoke this operation as the configured numeric service UID and GID'

agent_query() {
  /usr/sbin/netdata -u "$service_user" -W get directories "$1" ''
}

# Ask the Agent for the directories it will export to plugins. A restricted
# account must not silently fall through to stock config that root could read.
if [[ -e /etc/netdata/netdata.conf && ! -r /etc/netdata/netdata.conf ]]; then
  die 'the service account cannot read /etc/netdata/netdata.conf'
fi
NETDATA_USER_CONFIG_DIR=$(agent_query config)
NETDATA_STOCK_CONFIG_DIR=$(agent_query 'stock config')
NETDATA_LIB_DIR=$(agent_query lib)
plugins=$(agent_query plugins)
plugin_dir=/usr/libexec/netdata/plugins.d
case "$plugins " in
  "\"$plugin_dir\" "* | "$plugin_dir "*) ;;
  *) die 'Docker enrollment requires the stock image plugin directory first in the Agent configuration' ;;
esac
for dir in "$NETDATA_USER_CONFIG_DIR" "$NETDATA_STOCK_CONFIG_DIR" "$NETDATA_LIB_DIR"; do
  [[ $dir == /* && ! $dir =~ [[:cntrl:]] && -d $dir && -x $dir ]] ||
    die 'Agent configuration and data directories must be absolute and accessible to the service account'
done
export NETDATA_USER_CONFIG_DIR NETDATA_STOCK_CONFIG_DIR NETDATA_LIB_DIR
export HOME="$NETDATA_LIB_DIR" USER="$service_user" LOGNAME="$service_user"
cd /
if [[ $action == plan ]]; then
  exec "$plugin_dir/dem.plugin" runtime setup-plan --config-dir "$NETDATA_USER_CONFIG_DIR"
fi
if [[ $action == ensure ]]; then
  exec "$plugin_dir/dem.plugin" runtime ensure --allow-download --config-dir "$NETDATA_USER_CONFIG_DIR" \
    --expected-root /var/lib/netdata/dem/runtime --cancel-on-stdin-close
fi

# Resolve the configured owner without opening storage or changing enrollment.
runtime_root=/var/lib/netdata/dem/runtime
plan=$("$plugin_dir/dem.plugin" runtime setup-plan --config-dir "$NETDATA_USER_CONFIG_DIR")
[[ $plan == "netdata-dem-runtime-setup-v1
standalone
managed
$runtime_root" ]] || die 'paired Docker operations require the stock managed runtime root; use the explicit deployment owner for other modes or paths'

if [[ $action == fetch ]]; then
  [[ $output != */ && $output != */. && $output != */.. && ! -e $output && ! -L $output ]] ||
    die 'fetch output must be a new directory outside the managed runtime root'
  parent=${output%/*}
  canonical_parent=$(cd -- "${parent:-/}" && pwd -P) || die 'fetch output parent must already exist'
  canonical_output=${canonical_parent%/}/${output##*/}
  case "$canonical_output" in
    "$runtime_root" | "$runtime_root"/*) die 'retain fetched inputs outside the managed runtime root so legacy garbage collection cannot remove recovery inputs' ;;
  esac
fi
case "$action" in
  prepare) printf '%s\n' 'Docker paired deployment: stop all old consumers before importing these inputs; this helper does not stop or recreate containers.' >&2 ;;
  activate | rollback) printf '%s\n' 'Docker paired deployment: consumers must be stopped and drained; the deployment owner must start the matching pinned image after selection succeeds.' >&2 ;;
esac

# Keep stdout available for the CLI's report or bounded pair-plan protocol.
command=("$plugin_dir/dem.plugin" runtime "$action" --config-dir "$NETDATA_USER_CONFIG_DIR" "${arguments[@]}")
printf 'DEM browser runtime: run' >&2
for argument in "${command[@]}"; do
  case "$argument" in *://* | *token=* | *password=* | *secret=* | *authorization=*) argument='[redacted]' ;; esac
  printf ' %q' "$argument" >&2
done
printf '\n' >&2
if "${command[@]}"; then exit 0; else
  status=$?
  printf 'DEM browser runtime: %s failed in %q: status %s; use the paired deployment owner to recover before starting a matching image\n' "$action" "$PWD" "$status" >&2
  exit "$status"
fi
