#!/bin/sh
# EXZA Remote user-owned foreground connection. This script does not request
# administrator privileges, install background services or transmit passwords.
set -eu
url="https://remote.exza.de/downloads/exza-remote-client.zip"
sha="8819de1f1ca215027e0e68fe149e9727f0c65129968257cd760434e82ffccc45"
target="$HOME/.exza-remote-connection"
printf 'Downloading the latest verified EXZA Remote client build.
'
printf '\nEXZA REMOTE CONNECTION | SECURE SETUP\n'
if ! command -v node >/dev/null 2>&1 || ! node -e "process.exit(Number(process.versions.node.split('.')[0])>=22?0:1)" 2>/dev/null; then
 echo "Node.js 22 or newer is required. Install it from https://nodejs.org/ and rerun this command." >&2
 exit 1
fi
if ! command -v npm >/dev/null 2>&1; then echo "npm is required. Install Node.js with npm." >&2;exit 1;fi
if ! command -v curl >/dev/null 2>&1 || ! command -v unzip >/dev/null 2>&1; then echo "curl and unzip are required." >&2;exit 1;fi
agent_port="$(printenv EXZA_PORT || echo 8765)"
if command -v lsof >/dev/null 2>&1 && lsof -nP -iTCP:"$agent_port" -sTCP:LISTEN >/dev/null 2>&1; then
 echo "Port 8765 already has a listening process. EXZA will not start a competing agent."
 echo "If EXZA is already open, use that terminal and enter 'status' or 'new code'."
 exit 0
fi
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT INT TERM
curl -fLSs --retry 2 --max-time 65 -H "Cache-Control: no-cache" "$url" -o "$tmp/client.zip"
if command -v shasum >/dev/null 2>&1; then actual="$(shasum -a 256 "$tmp/client.zip" | awk '{print $1}')"
elif command -v sha256sum >/dev/null 2>&1; then actual="$(sha256sum "$tmp/client.zip" | awk '{print $1}')"
else echo "SHA-256 verification tool unavailable; stopping." >&2;exit 1;fi
if [ "$actual" != "$sha" ];then echo "EXZA download verification FAILED; refusing to run." >&2;exit 1;fi
mkdir -p "$target" "$tmp/client"
unzip -oq "$tmp/client.zip" -d "$tmp/client"
# The archive is vetted to contain only program files; credentials are
# generated locally and preserved between program updates.
cp -R "$tmp/client/." "$target/"
cd "$target"
npm ci --omit=dev --ignore-scripts --no-audit --no-fund --silent
printf '\nEXZA client verified and installed at: %s\n' "$target"
printf 'Open https://remote.exza.de/app/ in your browser and sign in.\n'
printf 'Enter the six-digit code from THIS terminal in My Devices,\n'
printf 'then type Y or N in this terminal to approve or reject. Keep it open.\n\n'
if [ -f "$target/cloudflare/device.json" ];then
 EXZA_CLOUD_ENABLE=1; export EXZA_CLOUD_ENABLE
else
 EXZA_PAIR_ENABLE=1; export EXZA_PAIR_ENABLE
fi
exec node ./agent.mjs
