#!/bin/sh
# Heartbeat agent installer for Linux and other Unix servers.
#   sudo sh install.sh --php --php-sender sender-acme-web-01.php
#   sudo sh install.sh --host --live --otel-env otel-acme-web.env
#   sudo sh install.sh --uninstall
set -eu

PREFIX=/opt/heartbeat
CONF=/etc/heartbeat
SPOOL=/var/spool/heartbeat
PKG_URL="${HEARTBEAT_PACKAGE_URL:-}"

php=0 host=0 live=0 full=0 uninstall=0
sender="" otel_env="" ca="" web_user="" app_user="heartbeat" php_bin="php" package="" php_configs=""

die() { echo "heartbeat: $*" >&2; exit 1; }

# Builds ext/heartbeat for one web PHP and enables it for every SAPI of that PHP (mod_php, FPM, CLI).
# The extension does nothing until the Heartbeat prepend registers a request, so loading it globally
# does not trace other sites. A failed build only disables SQL/HTTP steps; the install continues.
build_php_ext() {
  pc=$1
  [ -x "$pc" ] || { echo "Warning: php-config not executable: $pc" >&2; return 0; }
  ver=$("$pc" --version); ext_dir=$("$pc" --extension-dir); bin=$("$pc" --php-binary 2>/dev/null) || bin=""
  phpize="$(dirname "$pc")/phpize"; [ -x "$phpize" ] || phpize=$(command -v phpize 2>/dev/null || true)
  work=$(mktemp -d)
  cp -R "$PREFIX/php/ext/heartbeat/." "$work/"
  if [ -z "$phpize" ] || ! ( cd "$work" && "$phpize" >/dev/null 2>&1 && ./configure --with-php-config="$pc" >/dev/null 2>&1 && make >/dev/null 2>&1 ); then
    # Old phpize releases need autoconf 2.13. The Linux module can also
    # be compiled directly against the installed web PHP headers.
    case "$(uname -s):$ver" in
      Linux:5.*) mkdir -p "$work/modules"
        # php-config supplies a whitespace-separated list of compiler flags.
        cc -shared -fPIC -DCOMPILE_DL_HEARTBEAT $("$pc" --includes) -o "$work/modules/heartbeat.so" "$work/heartbeat.c" || rm -f "$work/modules/heartbeat.so" ;;
    esac
    if [ ! -s "$work/modules/heartbeat.so" ]; then
      rm -rf "$work"
      echo "Warning: could not build the tracing extension for PHP $ver (needs gcc, make, autoconf and php-devel). SQL/HTTP steps stay off." >&2
      return 0
    fi
  fi
  mkdir -p "$ext_dir"
  install -m 755 "$work/modules/heartbeat.so" "$ext_dir/heartbeat.so"; rm -rf "$work"
  line="extension=heartbeat.so"
  mm=$(echo "$ver" | cut -d. -f1,2)
  if [ -d "/etc/php/$mm/mods-available" ] && command -v phpenmod >/dev/null 2>&1; then
    ini="/etc/php/$mm/mods-available/heartbeat.ini"
    printf '; priority=90\n%s\n' "$line" > "$ini"; phpenmod -v "$mm" heartbeat
    for sapi in /etc/php/"$mm"/*/conf.d; do echo "$sapi/90-heartbeat.ini"; done >> "$CONF/php-ext.list"
  else
    scan=""; [ -z "$bin" ] || scan=$("$bin" --ini 2>/dev/null | sed -n 's/^Scan for additional .ini files in: *//p')
    case "$scan" in ""|"(none)") echo "Warning: add '$line' to the php.ini of PHP $ver, then reload the web server." >&2; ini="" ;;
      *) ini="${scan%%:*}/90-heartbeat.ini"; printf '%s\n' "$line" > "$ini" ;; esac
  fi
  { echo "$ext_dir/heartbeat.so"; [ -z "$ini" ] || echo "$ini"; } >> "$CONF/php-ext.list"
  [ -z "$bin" ] || "$bin" -m 2>/dev/null | grep -qx heartbeat || echo "Warning: PHP $ver did not load heartbeat.so" >&2
  echo "Installed heartbeat.so for PHP $ver. After reloading Apache or PHP-FPM, verify extension_loaded('heartbeat') in a web request."
}
usage() {
  cat <<'EOF'
Usage: install.sh [components] [options]
  --php                PHP agent (request capture + 10s encrypted push)
  --host               Server/DB/log collector (Python 3.10+)
  --live               In-flight SQL/HTTP forwarder for Java/Node.js/Python/.NET/Go
  --php-sender FILE    Sender file issued by Heartbeat for this server (sender-<kid>.php)
  --otel-env FILE      OTLP env file issued by Heartbeat (otel-<id>.env)
  --ca FILE            CA certificate of the Heartbeat collector (private CA only)
  --web-user USER      Web server user that runs PHP (default: auto-detect)
  --app-user USER      User that runs your Java/Node.js/Python/.NET/Go app; --live shares a spool with it (default: heartbeat)
  --php-bin PATH       PHP CLI 8.1+ used by the sender (default: php)
  --php-config PATH    php-config of the web PHP (5.0+) to build the SQL/HTTP tracing extension for;
                       repeat for several PHP versions (default: php-config on PATH)
  --full               Install every DB/cloud/Kubernetes driver for --host
  --package FILE|URL   heartbeat-agent.tar.gz (default: next to this script, or $HEARTBEAT_PACKAGE_URL)
  --uninstall          Stop services and remove programs (config and spool are kept)
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    --php) php=1 ;;
    --host) host=1 ;;
    --live) live=1 ;;
    --full) full=1 ;;
    --uninstall) uninstall=1 ;;
    --php-sender) sender="$2"; shift ;;
    --otel-env) otel_env="$2"; shift ;;
    --ca) ca="$2"; shift ;;
    --web-user) web_user="$2"; shift ;;
    --app-user) app_user="$2"; shift ;;
    --php-bin) php_bin="$2"; shift ;;
    --php-config) php_configs="$php_configs $2"; shift ;;
    --package) package="$2"; shift ;;
    -h|--help) usage; exit 0 ;;
    *) usage >&2; die "unknown option: $1" ;;
  esac
  shift
done

[ "$(id -u)" = 0 ] || die "run as root (sudo)"
has_systemd() { [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; }
os=$(uname -s)

units="heartbeat-php-collect heartbeat-php-send heartbeat-php-active heartbeat-host heartbeat-live"

if [ "$uninstall" = 1 ]; then
  if has_systemd; then
    for u in $units; do
      systemctl disable --now "$u.timer" 2>/dev/null || true
      systemctl disable --now "$u.service" 2>/dev/null || true
      rm -f "/etc/systemd/system/$u.timer" "/etc/systemd/system/$u.service"
    done
    systemctl daemon-reload
  fi
  for p in /Library/LaunchDaemons/io.heartbeat.*.plist; do
    [ -f "$p" ] && { launchctl bootout system "$p" 2>/dev/null || true; rm -f "$p"; }
  done
  if command -v crontab >/dev/null 2>&1 && crontab -l 2>/dev/null | grep -q heartbeat-run; then
    crontab -l | grep -v heartbeat-run | crontab -
  fi
  pkill -f "$PREFIX/bin/heartbeat-run" 2>/dev/null || true
  # Tracing extension files installed into each web PHP (see build_php_ext).
  if [ -f "$CONF/php-ext.list" ]; then
    while read -r f; do rm -f "$f"; done < "$CONF/php-ext.list"
    rm -f "$CONF/php-ext.list"
    echo "Removed the heartbeat PHP extension; reload Apache or PHP-FPM."
  fi
  rm -rf "$PREFIX"
  echo "Heartbeat removed. Kept $CONF and $SPOOL. Remove auto_prepend_file from your PHP settings."
  exit 0
fi

[ $((php + host + live)) -gt 0 ] || { usage >&2; die "choose at least one of --php, --host, --live"; }
[ "$php" = 0 ] || [ -r "$sender" ] || die "--php needs a readable --php-sender file"
[ $((host + live)) = 0 ] || [ -r "$otel_env" ] || die "--host/--live need a readable --otel-env file"
[ -z "$ca" ] || [ -r "$ca" ] || die "cannot read --ca $ca"

# Unpack the agent files.
work=$(mktemp -d); trap 'rm -rf "$work"' EXIT
here=$(cd "$(dirname "$0")" && pwd)
if [ -z "$package" ]; then
  if [ -d "$here/agents" ]; then package="$here"; elif [ -f "$here/heartbeat-agent.tar.gz" ]; then package="$here/heartbeat-agent.tar.gz"; else package="$PKG_URL"; fi
fi
[ -n "$package" ] || die "agent files not found; pass --package or set HEARTBEAT_PACKAGE_URL"
case "$package" in
  http://*|https://*) curl -fsSL "$package" -o "$work/pkg.tgz" || die "download failed: $package"; tar -xzf "$work/pkg.tgz" -C "$work" ;;
  *.tar.gz|*.tgz) tar -xzf "$package" -C "$work" ;;
  *) [ -d "$package/agents" ] || die "not an agent package: $package"; cp -R "$package/." "$work/" ;;
esac
src="$work"; [ -d "$src/agents" ] || src=$(find "$work" -maxdepth 2 -type d -name agents -exec dirname {} \; | head -n1)
[ -n "$src" ] && [ -d "$src/agents" ] || die "package has no agents directory"

mkdir -p "$PREFIX/bin" "$CONF"
chmod 755 "$PREFIX" "$CONF"
[ -z "$ca" ] || install -m 644 "$ca" "$CONF/ca.pem"
ca_path=""; [ -z "$ca" ] || ca_path="$CONF/ca.pem"

# Long-running fallback when systemd is not present (cron @reboot keeps it alive across reboots).
loop_line=""
add_loop() { loop_line="$loop_line
$1"; }

# ---------------------------------------------------------------- PHP agent
if [ "$php" = 1 ]; then
  command -v "$php_bin" >/dev/null 2>&1 || die "PHP CLI not found: $php_bin (use --php-bin)"
  "$php_bin" -r 'exit(PHP_VERSION_ID >= 80100 && function_exists("curl_init") && function_exists("gzencode") && in_array("aes-256-gcm", openssl_get_cipher_methods(), true) ? 0 : 1);' \
    || die "$php_bin must be PHP 8.1+ with curl, zlib and openssl (aes-256-gcm); the web PHP version does not matter"
  if [ -z "$web_user" ]; then
    for u in www-data apache nginx nobody; do id "$u" >/dev/null 2>&1 && { web_user=$u; break; }; done
  fi
  id "$web_user" >/dev/null 2>&1 || die "web user not found; pass --web-user"
  web_group=$(id -gn "$web_user")
  php_bin=$(command -v "$php_bin")

  rm -rf "$PREFIX/php"; cp -R "$src/agents/php" "$PREFIX/php"
  find "$PREFIX/php" -type d -exec chmod 755 {} \; ; find "$PREFIX/php" -type f -exec chmod 644 {} \;
  [ -n "$php_configs" ] || php_configs=$(command -v php-config 2>/dev/null || true)
  [ -n "$php_configs" ] || echo "Warning: php-config not found; requests are captured without SQL/HTTP steps. Install php-devel (php-dev) and rerun, or pass --php-config." >&2
  for pc in $php_configs; do build_php_ext "$pc"; done

  # Web workers and the sender share the spool; the group keeps it private to them.
  install -d -m 2770 -o "$web_user" -g "$web_group" "$SPOOL/php"
  # Web workers write before the first collect run creates these.
  for d in spool ready outbox outbox/.staging outbox/quarantine outbox/raw raw-spool raw-ready; do
    install -d -m 700 -o "$web_user" -g "$web_group" "$SPOOL/php/$d"
  done
  cfg="$CONF/php-agent.php"
  umask 077
  "$php_bin" -r '
    $s = require $argv[1];
    if (!is_array($s) || !isset($s["site"], $s["server"], $s["kid"], $s["url"], $s["push_key"], $s["ack_key"])) { fwrite(STDERR, "invalid sender file\n"); exit(1); }
    file_put_contents($argv[5], json_encode($s));
    $c = array("enabled"=>true, "push_spool_path"=>$argv[2], "push_format"=>"raw", "trace_enabled"=>true);
    if ($argv[3] !== "") $c["ca_file"] = $argv[3];
    file_put_contents($argv[4], "<?php\nreturn ".var_export($c, true).";\n");
  ' "$sender" "$SPOOL/php" "$ca_path" "$cfg.tmp" "$CONF/php-sender.json.tmp" || die "cannot read $sender"
  chmod 600 "$CONF/php-sender.json.tmp"; mv "$CONF/php-sender.json.tmp" "$CONF/php-sender.json"
  umask 022
  chown root:"$web_group" "$cfg.tmp"; chmod 640 "$cfg.tmp"; mv "$cfg.tmp" "$cfg"

  if has_systemd; then
    for mode in collect send active; do
      case $mode in collect) every="*:*:00/10" ;; send) every="*:*:00/10" ;; active) every="*:*:00/2" ;; esac
      cat > "/etc/systemd/system/heartbeat-php-$mode.service" <<EOF
[Unit]
Description=Heartbeat PHP agent $mode

[Service]
Type=oneshot
User=$web_user
Group=$web_group
StandardInput=file:$CONF/php-sender.json
ExecStart=$php_bin $PREFIX/php/bin/push.php $mode --credentials-stdin
TimeoutStartSec=9s
UMask=0007
NoNewPrivileges=true
EOF
      cat > "/etc/systemd/system/heartbeat-php-$mode.timer" <<EOF
[Unit]
Description=Run Heartbeat PHP agent $mode

[Timer]
OnCalendar=*-*-* $every
AccuracySec=200ms

[Install]
WantedBy=timers.target
EOF
    done
    systemctl daemon-reload
    systemctl enable --now heartbeat-php-collect.timer heartbeat-php-send.timer heartbeat-php-active.timer
  else
    if [ "$os" = Darwin ]; then
      for mode in collect send active; do
        interval=10; [ "$mode" != active ] || interval=2
        plist="/Library/LaunchDaemons/io.heartbeat.php-$mode.plist"
        cat > "$plist" <<EOF
<plist version="1.0"><dict>
<key>Label</key><string>io.heartbeat.php-$mode</string>
<key>ProgramArguments</key><array><string>/bin/sh</string><string>-c</string>
<string>exec /usr/bin/sudo -u $web_user "$php_bin" "$PREFIX/php/bin/push.php" $mode --credentials-stdin &lt; "$CONF/php-sender.json"</string></array>
<key>StartInterval</key><integer>$interval</integer><key>RunAtLoad</key><true/>
</dict></plist>
EOF
        launchctl bootout system "$plist" 2>/dev/null || true
        launchctl bootstrap system "$plist"
      done
    else
      add_loop "php:$web_user:$php_bin"
    fi
  fi
fi

# ------------------------------------------------- host collector / live forwarder
if [ $((host + live)) -gt 0 ]; then
  py=""
  for c in python3.13 python3.12 python3.11 python3.10 python3; do
    command -v "$c" >/dev/null 2>&1 && "$c" -c 'import sys; sys.exit(sys.version_info < (3, 10))' && { py=$(command -v "$c"); break; }
  done
  [ -n "$py" ] || die "Python 3.10+ is required for --host/--live"
  id heartbeat >/dev/null 2>&1 || {
    if command -v useradd >/dev/null 2>&1; then useradd --system --home-dir "$PREFIX" --shell /usr/sbin/nologin heartbeat
    elif [ "$os" = Darwin ]; then die "create a 'heartbeat' user on macOS first (sysadminctl -addUser heartbeat)"
    else die "create a 'heartbeat' system user first"; fi
  }
  rm -rf "$PREFIX/agents"; cp -R "$src/agents/host" "$PREFIX/agents"
  "$py" -m venv "$PREFIX/venv"
  if [ "$full" = 1 ]; then reqs="-r $PREFIX/agents/requirements.txt"
  else reqs=$(grep -E '^(psutil|sqlglot)==' "$PREFIX/agents/requirements.txt" | tr '\n' ' '); fi
  # shellcheck disable=SC2086
  "$PREFIX/venv/bin/pip" install --quiet --disable-pip-version-check $reqs || die "pip install failed"
  install -m 640 -o root -g "$(id -gn heartbeat)" "$otel_env" "$CONF/otel.env"
  # systemd EnvironmentFile does not accept 'export '.
  sed -i.bak 's/^export //' "$CONF/otel.env" && rm -f "$CONF/otel.env.bak"
  endpoint=$(sed -n 's/^OTEL_EXPORTER_OTLP_ENDPOINT=//p' "$CONF/otel.env" | tr -d "\"'")
  [ -n "$endpoint" ] || die "OTEL_EXPORTER_OTLP_ENDPOINT missing in $otel_env"
  install -d -m 700 -o heartbeat -g "$(id -gn heartbeat)" "$SPOOL/host"
  id "$app_user" >/dev/null 2>&1 || die "app user not found: $app_user"
  # The app processes and the live forwarder share this private directory.
  install -d -m 700 -o "$app_user" -g "$(id -gn "$app_user")" "$SPOOL/live"
  [ -z "$ca_path" ] || printf 'OTEL_EXPORTER_OTLP_CERTIFICATE=%s\n' "$ca_path" >> "$CONF/otel.env"
  printf 'APM_LIVE_DIR=%s\n' "$SPOOL/live" >> "$CONF/otel.env"

  # The host collector discovers standard web logs when it starts.
  if [ "$host" = 1 ]; then
    echo "Apache/Nginx: grant heartbeat read access to access/error logs and directory traversal, including after rotation."
    # SSH sign-in logs: journald on systemd hosts, otherwise auth.log (root:adm on Debian/Ubuntu).
    if getent group systemd-journal >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
      usermod -a -G systemd-journal heartbeat || echo "Warning: add heartbeat to systemd-journal to collect SSH logs" >&2
    elif [ -f /var/log/auth.log ] && getent group adm >/dev/null 2>&1; then
      usermod -a -G adm heartbeat || echo "Warning: add heartbeat to adm to collect SSH logs" >&2
    elif [ -f /var/log/secure ]; then
      echo "SSH: grant heartbeat read access to /var/log/secure (kept after rotation) to collect SSH logs."
    fi
  fi

  if [ "$host" = 1 ] && [ ! -f "$CONF/host.json" ]; then
    ca_json="null"; [ -z "$ca_path" ] || ca_json="\"$ca_path\""
    cat > "$CONF/host.json" <<EOF
{
  "endpoint": "$endpoint",
  "ca_file": $ca_json,
  "token_env": "APM_OTLP_TOKEN",
  "spool": "$SPOOL/host/queue.sqlite",
  "inputs": [
    {"kind": "server", "name": "$(uname -n)", "interval": 15}
  ]
}
EOF
    chmod 644 "$CONF/host.json"
  fi

  svc_host="$PREFIX/venv/bin/python $PREFIX/agents/collect.py $CONF/host.json"
  svc_live="$PREFIX/venv/bin/python $PREFIX/agents/live/forward.py --dir $SPOOL/live"
  if has_systemd; then
    for name in host live; do
      eval "on=\$$name"; [ "$on" = 1 ] || continue
      eval "cmd=\$svc_$name"
      run_as=heartbeat; [ "$name" = host ] || run_as="$app_user"
      cat > "/etc/systemd/system/heartbeat-$name.service" <<EOF
[Unit]
Description=Heartbeat $name agent
After=network-online.target
Wants=network-online.target

[Service]
User=$run_as
EnvironmentFile=$CONF/otel.env
ExecStart=$cmd
Restart=always
RestartSec=5s
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
EOF
    done
    systemctl daemon-reload
    [ "$host" = 0 ] || { systemctl enable heartbeat-host.service && systemctl restart heartbeat-host.service; }
    [ "$live" = 0 ] || systemctl enable --now heartbeat-live.service
  elif [ "$os" = Darwin ]; then
    for name in host live; do
      eval "on=\$$name"; [ "$on" = 1 ] || continue
      eval "cmd=\$svc_$name"
      run_as=heartbeat; [ "$name" = host ] || run_as="$app_user"
      plist="/Library/LaunchDaemons/io.heartbeat.$name.plist"
      launch_env="$CONF/otel.env"
      if [ "$name" = live ] && [ "$run_as" != heartbeat ]; then
        launch_env="$CONF/live.env"
        install -m 400 -o "$run_as" "$CONF/otel.env" "$launch_env"
      fi
      cat > "$plist" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>io.heartbeat.$name</string>
  <key>UserName</key><string>$run_as</string>
  <key>ProgramArguments</key><array>
    <string>/bin/sh</string><string>-c</string>
    <string>set -a; . $launch_env; set +a; exec $cmd</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
</dict></plist>
EOF
      launchctl bootout system "$plist" 2>/dev/null || true
      launchctl bootstrap system "$plist"
    done
  else
    [ "$host" = 0 ] || add_loop "cmd:heartbeat:$svc_host"
    [ "$live" = 0 ] || add_loop "cmd:$app_user:$svc_live"
  fi
fi

# ---------------------------------------------- non-systemd Unix (AIX, Solaris, BSD, old init)
if [ -n "$loop_line" ]; then
  cat > "$PREFIX/bin/heartbeat-run" <<EOF
#!/bin/sh
# Keeps Heartbeat agents running without systemd. Started from root's crontab @reboot.
set -a; [ -f $CONF/otel.env ] && . $CONF/otel.env; set +a
EOF
  echo "$loop_line" | while IFS= read -r spec; do
    case "$spec" in
      php:*)
        u=$(echo "$spec" | cut -d: -f2); b=$(echo "$spec" | cut -d: -f3-)
        cat >> "$PREFIX/bin/heartbeat-run" <<EOF
( while :; do su -s /bin/sh $u -c "$b $PREFIX/php/bin/push.php active --credentials-stdin" < "$CONF/php-sender.json" >/dev/null 2>&1; sleep 2; done ) &
( while :; do su -s /bin/sh $u -c "$b $PREFIX/php/bin/push.php collect --credentials-stdin" < "$CONF/php-sender.json"; su -s /bin/sh $u -c "$b $PREFIX/php/bin/push.php send --credentials-stdin" < "$CONF/php-sender.json" >/dev/null 2>&1; sleep 10; done ) &
EOF
        ;;
      cmd:*)
        u=$(echo "$spec" | cut -d: -f2); cmd=$(echo "$spec" | cut -d: -f3-)
        echo "( while :; do su -s /bin/sh $u -c \"$cmd\"; sleep 5; done ) &" >> "$PREFIX/bin/heartbeat-run"
        ;;
    esac
  done
  echo "wait" >> "$PREFIX/bin/heartbeat-run"
  chmod 755 "$PREFIX/bin/heartbeat-run"
  if command -v crontab >/dev/null 2>&1; then
    ( crontab -l 2>/dev/null | grep -v heartbeat-run; echo "@reboot $PREFIX/bin/heartbeat-run" ) | crontab -
  else
    echo "heartbeat: no systemd or cron; add $PREFIX/bin/heartbeat-run to your boot scripts" >&2
  fi
  pkill -f "$PREFIX/bin/heartbeat-run" 2>/dev/null || true
  nohup "$PREFIX/bin/heartbeat-run" >/dev/null 2>&1 &
fi

echo "Heartbeat agent installed in $PREFIX"
if [ "$php" = 1 ]; then
  cat <<EOF

Next step: load the PHP agent in the web PHP of this site, then reload Apache or PHP-FPM
(the reload also loads the SQL/HTTP tracing extension).
  Apache mod_php (VirtualHost):  php_admin_value auto_prepend_file "$PREFIX/php/agent/prepend.php"
  PHP-FPM (pool .conf):          php_admin_value[auto_prepend_file] = $PREFIX/php/agent/prepend.php
If the site already uses auto_prepend_file, require_once the Heartbeat prepend from that file instead.
EOF
fi
