#!/bin/bash # METARAtlas feeder setup. Install and start the managed dual-band relay. set -Eeuo pipefail root='' if [[ ${1:-} == --stage && $# -ge 2 && $2 == /* && $2 != / ]]; then root=${2%/} shift 2 elif [[ $EUID != 0 ]]; then echo 'Run this installer with sudo.' >&2; exit 2 fi uninstall=no if [[ $# == 1 && $1 == --uninstall ]]; then uninstall=yes elif [[ $# != 0 ]]; then echo 'Usage: sudo bash install.sh [--uninstall]' >&2; exit 2 fi unit=$root/etc/systemd/system/metaratlas-feed.service runner=$root/usr/local/libexec/metaratlas-feed reporter=$root/usr/local/libexec/metaratlas-feed-location state=$root/var/lib/metaratlas-feed config=$root/etc/default/metaratlas-feed legacy=$root/etc/systemd/system/metaratlas-feeder.service dropin=$unit.d/978-uat.conf backups=$root/var/backups/metaratlas-feed baseline=$backups/pre-install # Serialize backup snapshots, cleanup and publication for install and uninstall. mkdir -p -- "$backups" exec 9>"$backups/.setup.lock" flock -x 9 for target in "$unit" "$runner" "$reporter" "$config" "$state/uuid" "$root/etc/metaratlas-feed-uuid" "$baseline"; do for pending in "$target".metaratlas-pending.??????; do if [[ -f $pending && ! -L $pending && -O $pending ]]; then rm -f -- "$pending"; fi done done flush_publication_dirs() { local dir dir=$(dirname -- "$1") while :; do sync -- "$dir" || return [[ $dir != "${root:-/}" && $dir != / ]] || return 0 dir=$(dirname -- "$dir") done } write_managed_file() { local target=$1 mode=$2 pending pending=$(mktemp -- "$target.metaratlas-pending.XXXXXX") || return if cat > "$pending" && chmod "$mode" "$pending" && sync -- "$pending" && mv -fT -- "$pending" "$target"; then flush_publication_dirs "$target" return fi rm -f -- "$pending" return 1 } retire_baseline() { local directory # Keep the rollback pointer until restored names and contents are durable. for directory in "$(dirname -- "$unit")" "$(dirname -- "$config")" \ "$(dirname -- "$runner")" "$root/etc" "$state" "$backups"; do [[ ! -d $directory ]] || sync -f -- "$directory" || return done rm -f -- "$baseline" && sync -- "$backups" } if [[ $uninstall == yes ]]; then if [[ ! -f $baseline ]]; then echo 'No managed METARAtlas installation to remove.' exit 0 fi prior=$(cat "$baseline") [[ $prior =~ ^[0-9]{8}T[0-9]{6}Z[.][a-zA-Z0-9]+$ && -f $backups/$prior/restore.sh ]] || { echo 'No verified installer rollback is available.' >&2; exit 2; } bash "$backups/$prior/restore.sh" retire_baseline echo 'METARAtlas feeder changes rolled back. Existing decoders were left in place.' exit 0 fi migrate_dropin=no if [[ -e $dropin ]]; then expected=$(printf '[Service]\nExecStart=\nExecStart=/usr/local/libexec/metaratlas-feed-uat') if [[ $(grep -Ev '^[[:space:]]*($|#)' "$dropin") != "$expected" ]]; then echo 'The existing UAT override is not recognized. Setup left it unchanged.' >&2; exit 2 fi migrate_dropin=yes fi for f in "$unit" "$runner" "$reporter"; do if [[ -e $f ]] && ! grep -q '^# METARAtlas feeder setup v1' "$f"; then # Recognize the earlier documented Python service; back it up before migration. if [[ $f != "$unit" ]] || ! grep -qx 'ExecStart=/usr/bin/python3 /usr/local/bin/metaratlas-feed.py' "$f"; then echo "Existing $f is not managed by this setup; left unchanged." >&2; exit 2 fi fi done if [[ -f $legacy ]] && ! grep -Eq '^ExecStart=/usr/bin/python3 -u /opt/metaratlas-feeder/relay.py$|^ExecStart=/bin/bash /opt/metaratlas-feeder/socat-relay.sh$' "$legacy"; then echo 'An unknown metaratlas-feeder service already exists; left unchanged.' >&2; exit 2 fi # Validate all previous identities before changing anything. Never split an account link. id='' for f in "$state/uuid" "$root/var/lib/metaratlas-feeder/uuid" "$root/etc/metaratlas-feed-uuid"; do if [[ -s $f ]]; then previous=$(cat "$f") [[ $previous =~ ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ && $previous != 00000000-0000-0000-0000-000000000000 ]] || { echo 'Existing feeder ID is invalid; left unchanged.' >&2; exit 2; } [[ -z $id || $id == "$previous" ]] || { echo 'Different previous feeder IDs found; left unchanged. Contact support before migrating.' >&2; exit 2; } id=$previous fi done if [[ -z $root ]]; then command -v systemctl >/dev/null && [[ -d /run/systemd/system ]] || { echo 'This installer needs Linux with systemd. For adsb.im use Expert settings.' >&2; exit 2; } missing=() for pkg in curl python3; do command -v "$pkg" >/dev/null || missing+=("$pkg"); done if (( ${#missing[@]} )); then command -v apt-get >/dev/null || { echo 'Install curl and python3 using your package manager first.' >&2; exit 2; } apt-get update DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "${missing[@]}" fi fi # A restrictive root umask must not hide a newly created executable directory # from DynamicUser. Existing shared directory permissions are left alone. if [[ ! -d $(dirname "$runner") ]]; then install -d -m 755 "$(dirname "$runner")"; fi mkdir -p "$(dirname "$unit")" "$(dirname "$runner")" "$(dirname "$config")" "$state" "$root/var/backups/metaratlas-feed" chmod 700 "$state" backup=$(mktemp -d "$root/var/backups/metaratlas-feed/$(date -u +%Y%m%dT%H%M%SZ).XXXXXX") chmod 700 "$backup" files=("$unit" "$runner" "$reporter" "$config" "$state/uuid" "$state/uuid-claim" "$state/provision-retry" "$state/location.json" "$root/etc/metaratlas-feed-uuid") [[ $migrate_dropin == yes ]] && files+=("$dropin") was_active=no; was_enabled=no; old_active=no; old_enabled=no if [[ -z $root ]]; then systemctl is-active --quiet metaratlas-feed && was_active=yes || true systemctl is-enabled --quiet metaratlas-feed 2>/dev/null && was_enabled=yes || true systemctl is-active --quiet metaratlas-feeder && old_active=yes || true systemctl is-enabled --quiet metaratlas-feeder 2>/dev/null && old_enabled=yes || true fi printf '#!/bin/bash\nset -euo pipefail\n' > "$backup/restore.sh" if [[ -z $root ]]; then echo 'systemctl stop metaratlas-feed.service || true' >> "$backup/restore.sh" echo 'systemctl disable metaratlas-feed.service 2>/dev/null || true' >> "$backup/restore.sh" fi for f in "${files[@]}"; do if [[ -e $f ]]; then save=$(basename "$f") [[ $f != "$config" ]] || save=default-config cp -a "$f" "$backup/$save" printf 'cp -a -- %q %q\n' "$backup/$save" "$f" >> "$backup/restore.sh" else printf 'rm -f -- %q\n' "$f" >> "$backup/restore.sh" fi done if [[ -z $root ]]; then echo 'systemctl daemon-reload' >> "$backup/restore.sh" [[ $was_enabled == yes ]] && echo 'systemctl enable metaratlas-feed.service' >> "$backup/restore.sh" [[ $old_enabled == yes ]] && echo 'systemctl enable metaratlas-feeder.service' >> "$backup/restore.sh" [[ $was_active == yes ]] && echo 'systemctl start metaratlas-feed.service' >> "$backup/restore.sh" [[ $old_active == yes ]] && echo 'systemctl start metaratlas-feeder.service' >> "$backup/restore.sh" fi chmod 700 "$backup/restore.sh" saved_baseline=no rollback() { local rc=$? trap - ERR echo "Setup failed; restoring the previous relay." >&2 if bash "$backup/restore.sh" && [[ $saved_baseline == yes ]]; then retire_baseline || echo 'Could not confirm durable rollback cleanup.' >&2 fi exit "$rc" } trap rollback ERR if [[ ! -e $baseline ]]; then # Flush the snapshot before publishing the original-state pointer. sync -f -- "$backup" write_managed_file "$baseline" 600 <<< "$(basename "$backup")" saved_baseline=yes fi if [[ ! -e $state/uuid && -n $root && -z $id ]]; then id=$(cat /proc/sys/kernel/random/uuid) # Offline staging fixture only. fi if [[ ! -e $state/uuid && -n $id ]]; then write_managed_file "$state/uuid" 600 <<< "$id" fi if [[ -f $state/uuid ]]; then chmod 600 "$state/uuid"; fi # Existing legacy files are read for migration; new real installs keep one private copy. if [[ -n $root && -f $state/uuid && ! -e $root/etc/metaratlas-feed-uuid ]]; then write_managed_file "$root/etc/metaratlas-feed-uuid" 600 < "$state/uuid" fi if [[ ! -e $config ]]; then write_managed_file "$config" 644 <<'CONFIG' # METARAtlas feeder setup v1. Source is the decoder's local Beast output. METARATLAS_SOURCE_HOST=127.0.0.1 METARATLAS_SOURCE_PORT=30005 CONFIG fi write_managed_file "$runner" 755 <<'RUNNER' #!/usr/bin/python3 # METARAtlas feeder setup v1. Managed dual-band relay. import errno import fcntl from functools import partial from http.client import HTTPException import json import os from pathlib import Path import random import re import secrets import select import signal import socket import subprocess import sys import tempfile import threading import time from urllib.error import HTTPError, URLError from urllib.request import HTTPRedirectHandler, Request, build_opener import uuid def port(name, default): value = int(os.environ.get(name, default)) if not 1 <= value <= 65535: raise ValueError("Invalid feed port") return value def keepalive(sock): sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) for name, value in (("TCP_KEEPIDLE", 30), ("TCP_KEEPINTVL", 10), ("TCP_KEEPCNT", 3)): if hasattr(socket, name): sock.setsockopt(socket.IPPROTO_TCP, getattr(socket, name), value) SERVICE = "metaratlas-feed.service" STATUS_PREFIX = "METARAtlas: " def show_status(): try: result = subprocess.run( ("systemctl", "show", SERVICE, "--property=LoadState", "--property=ActiveState", "--property=StatusText"), check=True, capture_output=True, text=True, timeout=4, ) except (OSError, subprocess.SubprocessError): print("METARAtlas feeder status is unavailable from systemd.") return 1 fields = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line) if fields.get("LoadState") != "loaded": print("The METARAtlas feeder service is not installed.") return 1 active = fields.get("ActiveState") if active not in ("active", "activating"): print("The METARAtlas feeder service is stopped or failed.") return 1 message = fields.get("StatusText", "") print(message if message.startswith(STATUS_PREFIX) else "The METARAtlas feeder is starting.") return 0 class ServiceStatus: def __init__(self): address = os.environ.get("NOTIFY_SOCKET", "") self.address = "\0" + address[1:] if address.startswith("@") else address self.bands = {"1090": "Starting", "978": "Starting"} self.lock = threading.Lock() def publish(self, message): if not self.address: return try: with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as notifier: notifier.setblocking(False) notifier.sendto(("STATUS=" + STATUS_PREFIX + message).encode(), self.address) except OSError: pass # Status reporting must never interrupt either relay. def update(self, band, state): if not self.address: return with self.lock: if self.bands[band] == state: return self.bands[band] = state self.publish(" | ".join(f"{band}: {state}" for band, state in self.bands.items())) def connection_status(stage, error): if stage == "decoder": return "Decoder unavailable" if stage == "feed": if isinstance(error, socket.gaierror): return "Cannot look up the feed server" if error.errno in (errno.ENETDOWN, errno.ENETUNREACH, errno.EHOSTUNREACH): return "Network unavailable" return "Cannot connect to the feed server" return "Connection interrupted; retrying" def relay(source, destination, prefix, stop, report=lambda state: None): delay = 3 while not stop.is_set(): stage = "decoder" try: with socket.create_connection(source, timeout=5) as incoming: keepalive(incoming) incoming.settimeout(1) stage = "feed" with socket.create_connection(destination, timeout=5) as outgoing: stage = "stream" keepalive(outgoing) outgoing.sendall(prefix) delay = 3 forwarding = False report("Connected; waiting for decoder data") while not stop.is_set(): readable, _, _ = select.select((incoming, outgoing), (), (), 1) if outgoing in readable: report("Feed server closed the connection; retrying") break # The upstream is write-only. A close must wake a quiet relay. if incoming not in readable: continue # A connected, quiet decoder is normal. data = incoming.recv(65536) if not data: report("Decoder disconnected; retrying") break outgoing.sendall(data) if not forwarding: report("Forwarding decoder data") forwarding = True except OSError as error: report(connection_status(stage, error)) stop.wait(random.uniform(delay * .8, delay * 1.2)) delay = min(delay * 2, 30) RETRY_FIRST_S = 5 RETRY_MAX_S = 300 def provision_problem(error): """Plain reason and the server's minimum wait. Never includes the ID or retry token.""" if isinstance(error, HTTPError): header = (error.headers or {}).get("Retry-After", "") wait = min(int(header), 3600) if header.isascii() and header.isdecimal() else 0 if error.code == 429: return "metaratlas.com is busy and has not issued a feeder ID yet (HTTP 429)", wait if error.code >= 500: return f"metaratlas.com had a server error, no feeder ID yet (HTTP {error.code})", wait return f"metaratlas.com refused to issue a feeder ID (HTTP {error.code})", wait if isinstance(error, (URLError, ConnectionError, TimeoutError, HTTPException)): return "Cannot reach metaratlas.com to get a feeder ID", 0 if isinstance(error, OSError): return "Cannot save the feeder ID on this device", 0 return "Feeder identity is invalid or the server reply was not understood", 0 def provision_until_issued(state, status): """Back off from seconds to minutes instead of letting systemd restart us every few seconds.""" delay = RETRY_FIRST_S while True: try: return provision(state) except (OSError, ValueError, TypeError, KeyError, HTTPException) as error: reason, minimum = provision_problem(error) wait = max(random.uniform(delay * .8, delay * 1.2), minimum) message = f"{reason}; trying again in {max(1, round(wait))} s" status.publish(message) print(message, file=sys.stderr, flush=True) time.sleep(wait) delay = min(delay * 2, RETRY_MAX_S) class NoRedirect(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def write_private(path, value): temporary = None try: with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".identity-", delete=False) as tmp: temporary = Path(tmp.name) tmp.write(value + "\n") tmp.flush() os.fsync(tmp.fileno()) os.replace(temporary, path) finally: if temporary is not None: temporary.unlink(missing_ok=True) def code_path(state): return state.with_name(state.name + "-claim") def provision(state): retry_path = state.with_name("provision-retry") if state.is_file(): identity = uuid.UUID(state.read_text().strip()) retry_path.unlink(missing_ok=True) return identity lock = os.open(state.with_name(".provision-lock"), os.O_CREAT | os.O_RDWR, 0o600) with os.fdopen(lock, "w") as held: fcntl.flock(held, fcntl.LOCK_EX) if state.exists(): identity = uuid.UUID(state.read_text().strip()) retry_path.unlink(missing_ok=True) return identity if not retry_path.exists(): write_private(retry_path, secrets.token_hex(32)) retry_token = retry_path.read_text().strip() if not re.fullmatch(r"[0-9a-f]{64}", retry_token): raise ValueError("Invalid provisioning retry token") sync_state_directory(state) payload = json.dumps({"schema": 2, "retry_token": retry_token}, separators=(",", ":")).encode("ascii") request = Request("https://metaratlas.com/api/account/feeder-setup-identity", data=payload, headers={"Content-Type": "application/json"}) with build_opener(NoRedirect()).open(request, timeout=10) as response: if response.status != 201: raise ValueError("Identity not issued") body = json.loads(response.read(512)) identity = uuid.UUID(body["identity"]) code = body["claim_code"] if body["schema"] != 1 or identity.version != 4 or not re.fullmatch(r"[A-Z2-7]{12}", code): raise ValueError("Invalid issued identity") write_private(code_path(state), code) write_private(state, str(identity)) sync_state_directory(state) retry_path.unlink(missing_ok=True) return identity def sync_state_directory(state): directory = os.open(state.parent, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(directory) finally: os.close(directory) def main(): state = Path(os.environ.get("METARATLAS_UUID_FILE", "/var/lib/metaratlas-feed/uuid")) if sys.argv[1:] == ["--claim-code"]: if not sys.stdout.isatty(): raise SystemExit("Display the claim code only in a local interactive terminal") try: code = code_path(state).read_text().strip() if not re.fullmatch(r"[A-Z2-7]{12}", code): raise ValueError("Invalid claim code") except (ValueError, OSError): raise SystemExit("No claim code is available for this install") from None print(code) return if sys.argv[1:] == ["--status"]: raise SystemExit(show_status()) if len(sys.argv) != 1: raise SystemExit("Usage: metaratlas-feed [--claim-code | --status]") status = ServiceStatus() status.publish("Preparing feeder identity") try: identity = provision_until_issued(state, status) if not identity.int: raise ValueError("Invalid identity") key = str(identity).encode("ascii") source_host = os.environ.get("METARATLAS_SOURCE_HOST", "127.0.0.1") feed_host = os.environ.get("METARATLAS_FEED_HOST", "feed.metaratlas.com") legacy_source = port("METARATLAS_SOURCE_PORT", 30005) legacy_feed = port("METARATLAS_FEED_PORT", 30004) legacy_uat = legacy_source == 30978 bands = [ (port("METARATLAS_BEAST_SOURCE_PORT", 30005 if legacy_uat else legacy_source), port("METARATLAS_BEAST_FEED_PORT", 30004 if legacy_feed == 30978 else legacy_feed), bytes((26, 228)) + key), (port("METARATLAS_UAT_SOURCE_PORT", legacy_source if legacy_uat else 30978), port("METARATLAS_UAT_FEED_PORT", legacy_feed if legacy_feed == 30978 else 30978), b"METARATLAS-KEY " + key + b"\n"), ] except (OSError, ValueError, TypeError, KeyError): status.publish("Feeder identity or settings unavailable; retrying") raise SystemExit("Feeder identity or relay configuration unavailable; retrying through the service") from None if bands[0][0] == bands[1][0]: status.publish("The Beast and UAT decoder ports must be different") raise SystemExit("The Beast and UAT sources must use different ports") stop = threading.Event() for signum in (signal.SIGTERM, signal.SIGINT): signal.signal(signum, lambda *_: stop.set()) reporter = Path(os.environ.get("METARATLAS_LOCATION_REPORTER", "/usr/local/libexec/metaratlas-feed-location")) child = None if (os.environ.get("METARATLAS_REPORT_LOCATION", "1") == "1" and source_host in ("127.0.0.1", "localhost") and reporter.is_file()): child = subprocess.Popen(("/usr/bin/python3", str(reporter))) status.publish("Checking 1090 and 978 decoders") workers = [ threading.Thread(target=relay, args=((source_host, local), (feed_host, remote), prefix, stop, partial(status.update, band))) for band, (local, remote, prefix) in zip(("1090", "978"), bands) ] try: for worker in workers: worker.start() while not stop.wait(1): if any(not worker.is_alive() for worker in workers): raise RuntimeError("Feeder worker stopped") finally: stop.set() if child is not None: child.terminate() for worker in workers: if worker.is_alive(): worker.join() if __name__ == "__main__": main() RUNNER write_managed_file "$reporter" 755 <<'LOCATION' # METARAtlas feeder setup v1. Optional private location reporter. #!/usr/bin/env python3 """Optional local antenna capture and private HTTPS report. Never logs a point/UUID.""" import argparse import json import math import os from pathlib import Path import re import time import urllib.error import urllib.request def point(data): try: lat, lon = data['lat'], data['lon'] if isinstance(lat, bool) or isinstance(lon, bool): return None lat, lon = float(lat), float(lon) if not (math.isfinite(lat) and math.isfinite(lon) and -90 <= lat <= 90 and -180 <= lon <= 180): return None return {'lat': round(lat, 5), 'lon': round(lon, 5)} except (KeyError, TypeError, ValueError): return None def capture(root=''): for name in ['/run/dump1090-fa/receiver.json', '/run/readsb/receiver.json', '/run/skyaware/receiver.json']: try: result = point(json.loads(Path(root + name).read_text())) if result is not None: return result except (OSError, ValueError): pass if not root: for url in ['http://127.0.0.1/skyaware/data/receiver.json', 'http://127.0.0.1/dump1090-fa/data/receiver.json', 'http://127.0.0.1:8080/data/receiver.json']: try: with urllib.request.urlopen(url, timeout=2) as response: result = point(json.loads(response.read(8192))) if result is not None: return result except (OSError, ValueError): pass for name in ['/etc/default/dump1090-fa', '/etc/default/readsb']: try: text = '\n'.join(line.split('#', 1)[0] for line in Path(root + name).read_text().splitlines()) values = {} for key in ['lat', 'lon']: match = re.search(r'--' + key + r'(?:=|\s+)(-?\d+(?:\.\d+)?)', text) if match: values[key] = match[1] result = point(values) if result is not None: return result except OSError: pass return None class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, request, fp, code, message, headers, newurl): return None def report_once(location, uuid, url): request = urllib.request.Request(url, data=json.dumps(location).encode(), method='POST', headers={ 'Authorization': 'Bearer ' + uuid, 'Content-Type': 'application/json', 'User-Agent': 'METARAtlas feeder setup', }) try: with urllib.request.build_opener(NoRedirect).open(request, timeout=10) as response: return response.status == 200 and json.loads(response.read(512)).get('accepted') is True except (OSError, ValueError): return False def main(): parser = argparse.ArgumentParser() parser.add_argument('--capture') parser.add_argument('--root', default='') args = parser.parse_args() if args.capture: value = capture(args.root) if value is not None: path = Path(args.capture) temp = path.with_suffix('.tmp') temp.write_text(json.dumps(value) + '\n') temp.chmod(0o600) temp.replace(path) else: Path(args.capture).unlink(missing_ok=True) return state = Path(os.environ.get('METARATLAS_STATE', '/var/lib/metaratlas-feed')) try: location = point(json.loads((state / 'location.json').read_text())) uuid = (state / 'uuid').read_text().strip() if location is None: return except (OSError, ValueError): return url = 'https://metaratlas.com/api/account/feeder-setup-location' while True: time.sleep(30) # valid receiver data must arrive before metadata is accepted if report_once(location, uuid, url): time.sleep(21600) if __name__ == '__main__': main() LOCATION # Missing/invalid location is harmless. No coordinates are printed or put in URLs. python3 "$reporter" --capture "$state/location.json" --root "$root" || true # On a repeated install DynamicUser may reuse its UID. Keep newly captured # private metadata owned by the existing state owner before starting again. if [[ -f $state/location.json ]]; then chown --reference="$state" "$state/location.json"; fi write_managed_file "$unit" 644 <<'UNIT' # METARAtlas feeder setup v1 [Unit] Description=METARAtlas ADS-B feed (existing 1090 and 978 decoder outputs) Wants=network-online.target After=network-online.target StartLimitIntervalSec=0 [Service] Type=simple NotifyAccess=main DynamicUser=yes StateDirectory=metaratlas-feed StateDirectoryMode=0700 EnvironmentFile=-/etc/default/metaratlas-feed ExecStart=/usr/local/libexec/metaratlas-feed Restart=always RestartSec=5 TimeoutStopSec=10 KillMode=control-group NoNewPrivileges=yes ProtectSystem=strict ProtectHome=yes PrivateTmp=yes RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 [Install] WantedBy=multi-user.target UNIT if [[ $migrate_dropin == yes ]]; then rm -- "$dropin"; fi if [[ -z $root ]]; then systemctl daemon-reload if [[ $old_active == yes || $old_enabled == yes ]]; then systemctl disable --now metaratlas-feeder.service; fi if [[ $was_active == yes ]] && { [[ $migrate_dropin == yes ]] || ! cmp -s "$runner" "$backup/$(basename "$runner")" || ! cmp -s "$unit" "$backup/$(basename "$unit")" || ! cmp -s "$reporter" "$backup/$(basename "$reporter")"; }; then systemctl restart metaratlas-feed.service fi systemctl enable --now metaratlas-feed.service fi trap - ERR # A real install is not complete until this device has an ID; say so plainly. have_id=yes if [[ -z $root && ! -s $state/uuid ]]; then for _ in {1..20}; do [[ -s $state/uuid ]] && break sleep 1 done [[ -s $state/uuid ]] || have_id=no fi if [[ $have_id == yes ]]; then echo 'METARAtlas feeder setup complete. The relay starts automatically on this device.' else echo 'METARAtlas relay installed, but this device does NOT have a feeder ID yet, so it is not feeding.' >&2 "$runner" --status >&2 || true echo 'It keeps trying by itself. Check again with the status command below.' >&2 fi echo 'Check received data and choose Pair: https://metaratlas.com/accounts/feeder/' echo 'Location is copied if configured; fine-tune it on the site. Setup never pairs an account.' printf 'Rollback saved: sudo bash %s/restore.sh\n' "$backup" echo 'Status: /usr/local/libexec/metaratlas-feed --status' echo 'Stop: sudo systemctl disable --now metaratlas-feed'