#!/bin/sh
set -eu
# Installs one collector file into your user account. No sudo, service changes,
# firewall changes, telemetry, or automatic execution.
destination="${ZYRASEC_INSTALL_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/zyrasec}"
expected_version='0.3.0-beta.1'
command -v python3 >/dev/null 2>&1 || { echo 'Python 3.9+ is required.' >&2; exit 1; }
python3 -c 'import sys; sys.exit(sys.version_info < (3, 9))' || { echo 'Python 3.9+ is required.' >&2; exit 1; }
mkdir -p "$destination"
temporary=$(mktemp "$destination/.download.XXXXXX")
trap 'rm -f "$temporary"' EXIT HUP INT TERM
collector_file="${ZYRASEC_COLLECTOR_PATH:-}"
if [ -z "$collector_file" ] && [ -f "$0" ]; then
  candidate="$(dirname "$0")/zyrasec.py"
  if [ -f "$candidate" ]; then collector_file="$candidate"; fi
fi
if [ -n "$collector_file" ]; then
  cp -- "$collector_file" "$temporary"
else
  command -v curl >/dev/null 2>&1 || { echo 'curl is required for a remote download.' >&2; exit 1; }
  collector_url="${ZYRASEC_DOWNLOAD_URL:-https://github.com/cryptobredda/zyrasec/releases/download/v0.3.0-beta.1/zyrasec.py}"
  case "$collector_url" in https://*) ;; *) echo 'An HTTPS download URL is required.' >&2; exit 1 ;; esac
  curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --tlsv1.2 "$collector_url" -o "$temporary"
fi
# Parse, but never import or execute the downloaded collector during installation.
python3 - "$temporary" "$expected_version" <<'PY'
import ast
from pathlib import Path
import sys
tree=ast.parse(Path(sys.argv[1]).read_text())
versions=[ast.literal_eval(node.value) for node in tree.body if isinstance(node,ast.Assign) and any(isinstance(target,ast.Name) and target.id=='VERSION' for target in node.targets)]
if versions!=[sys.argv[2]]:
    raise SystemExit('Collector version mismatch. Download the matching release files.')
PY
chmod 700 "$temporary"
mv "$temporary" "$destination/zyrasec.py"
echo "Installed ZyraSec beta collector to $destination/zyrasec.py"
echo "Run: python3 \"$destination/zyrasec.py\" scan --output zyrasec-host-report.json"
echo 'No scan, upload, service change, or package update was performed.'
