#!/bin/sh
set -eu

if [ "$(id -u)" -ne 0 ]; then
	echo "run this installer as root" >&2
	exit 77
fi

script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
binary=${EDGEGUARD_AGENT_BINARY:-"$script_dir/edgeguard-agent"}

if [ ! -x "$binary" ]; then
	echo "edgeguard-agent binary not found: $binary" >&2
	exit 66
fi
if [ ! -x /sbin/openrc-run ]; then
	echo "OpenRC is required; this installer is intended for Alpine Linux" >&2
	exit 69
fi

install -d -m 0700 -o root -g root /var/lib/edgeguard-agent
install -d -m 0755 -o root -g root /usr/bin /etc/init.d /etc/periodic/15min
install -m 0755 -o root -g root "$binary" /usr/bin/edgeguard-agent
install -m 0755 -o root -g root "$script_dir/edgeguard-agent.initd" /etc/init.d/edgeguard-agent
install -m 0755 -o root -g root "$script_dir/edgeguard-agent-report" /etc/periodic/15min/edgeguard-agent-report

echo "EdgeGuard Agent installed for Alpine/OpenRC."
echo "Run: edgeguard-agent discover"
echo "Then: edgeguard-agent connect"
echo "Finally: rc-update add edgeguard-agent default && rc-service edgeguard-agent start"
