#!/bin/sh
# Owner: MeshDesk primary agent. Purpose: 2026-09-20 SimpleHelp-parity downloads/install hotfix. Removal condition: replace with manager-rendered authenticated download portal and native CI-published installers.
set -eu
host="https://meshdesk.devscloud.cc"
enrollment_key="SPPvw8k9zIKKdx4y9-nXVqteJig0aXUc"
pubkey="c2feb21c81fc82e8e2478791fab7109301bc6aca045892048846eaa16b22dc4d"
raw_host="$(hostname -s 2>/dev/null || hostname 2>/dev/null || echo endpoint)"
safe_host="$(printf '%s' "$raw_host" | tr -c 'A-Za-z0-9._-' '-' | sed 's/-\+/-/g; s/^-//; s/-$//' | cut -c1-48)"
[ -n "$safe_host" ] || safe_host=endpoint
machine_id="linux-$safe_host"
arch="$(uname -m)"
case "$arch" in
  x86_64|amd64) goarch="amd64"; artifact="meshdesk-agent-linux-amd64" ;;
  aarch64|arm64) goarch="arm64"; artifact="meshdesk-agent-linux-arm64" ;;
  *) echo "unsupported architecture: $arch" >&2; exit 2 ;;
esac
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT
curl -fsSL -H "Authorization: Bootstrap $enrollment_key" "$host/api/v1/bootstrap/agent?os=linux&arch=$goarch" -o "$tmp"
expected="$(curl -fsSL "$host/downloads/artifacts/$artifact.sha256" | awk '{print $1}')"
actual="$(sha256sum "$tmp" | awk '{print $1}')"
if [ "$expected" != "$actual" ]; then
  echo "checksum mismatch for $artifact" >&2
  exit 1
fi
install -m 0755 "$tmp" /usr/local/bin/meshdesk-agent
install -d -m 0700 /etc/meshdesk
cat >/etc/meshdesk/agent.env <<ENV
MESHDESK_FILE_ROOT=/
MESHDESK_AGENT_ENROLLMENT_KEY=$enrollment_key
ENV
chmod 0600 /etc/meshdesk/agent.env
cat >/etc/systemd/system/meshdesk-agent.service <<UNIT
[Unit]
Description=MeshDesk Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=root
Group=root
EnvironmentFile=/etc/meshdesk/agent.env
ExecStart=/usr/local/bin/meshdesk-agent --host $host --machine-id $machine_id --name AUTODETECT --server-pubkey $pubkey --force-verification --silent
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now meshdesk-agent.service
echo "MeshDesk agent installed and started against $host as $machine_id"
