#!/bin/sh
# TurnIt heartbeat installer, version 1.0.0. Requires POSIX sh and curl.
# Usage: sh install.sh HEARTBEAT_URL --interval SECONDS [--cron | --uninstall]
set -eu
umask 077
fail() { printf '%s\n' "$*" >&2; exit 1; }
usage() {
printf '%s\n' 'Usage: sh install.sh HEARTBEAT_URL --interval SECONDS [--cron]' \
' sh install.sh HEARTBEAT_URL --uninstall [--cron]' \
'Linux uses systemd (sudo required), or user cron when systemd is unavailable.' \
'Use --cron on Linux to explicitly select user cron. macOS uses a user LaunchAgent.'
}
endpoint= interval= uninstall=false force_cron=false
while [ "$#" -gt 0 ]; do
case "$1" in
--help|-h) usage; exit 0 ;;
--interval)
[ "$#" -ge 2 ] || fail 'Missing interval.'
interval=$2; shift 2 ;;
--uninstall) uninstall=true; shift ;;
--cron) force_cron=true; shift ;;
--*) fail 'Unknown option. Use --help.' ;;
*) [ -z "$endpoint" ] || fail 'Only one heartbeat URL is allowed.'; endpoint=$1; shift ;;
esac
done
[ -n "$endpoint" ] || { usage; exit 1; }
case "$endpoint" in https://?*|http://?*) ;; *) fail 'An absolute HTTP(S) heartbeat URL is required.' ;; esac
# Reject characters that could inject curl configuration or split an argument.
if printf '%s' "$endpoint" | tr '\n' ' ' | LC_ALL=C grep '[[:space:][:cntrl:]"\\]' >/dev/null; then
fail 'Invalid URL characters. Use the URL copied from the device guide.'
fi
identity=$(printf '%s\n' "$endpoint" | sed -n 's/^[^?]*?\([^#]*\).*$/\1/p' | tr '&' '\n' | sed -n 's/^v=//p')
printf '%s\n' "$identity" | LC_ALL=C grep -Eq '^[1-9][0-9]{0,19}-[a-zA-Z0-9_-]{1,128}$' || fail 'The URL must contain one valid device parameter v.'
# grep validates individual lines, so reject duplicate v parameters separately.
[ "$(printf '%s\n' "$identity" | wc -l | tr -d ' ')" = 1 ] || fail 'Duplicate device parameter v.'
if [ "$uninstall" = false ]; then
case "$interval" in ''|*[!0-9]*|0*) fail 'Provide --interval as a positive integer (seconds).' ;; esac
[ "${#interval}" -le 5 ] && [ "$interval" -le 86400 ] || fail 'Interval must be at most 86400 seconds.'
fi
platform=$(uname -s)
case "$platform" in Linux|Darwin) ;; *) fail 'Only Linux and macOS are supported.' ;; esac
[ -n "${HOME:-}" ] && [ "${HOME#/}" != "$HOME" ] || fail 'An absolute HOME directory is required.'
case "$HOME" in *'
'*) fail 'Invalid HOME directory.' ;; esac
key=turnit-heartbeat-$identity
label=app.turnit.heartbeat.$identity
mode=cron
if [ "$platform" = Darwin ]; then
[ "$force_cron" = false ] || fail '--cron is only supported on Linux.'
[ "$(id -u)" != 0 ] || fail 'Run the macOS installer as your desktop user, without sudo.'
command -v launchctl >/dev/null 2>&1 || fail 'launchctl is required.'
launchctl print "gui/$(id -u)" >/dev/null 2>&1 || fail 'Log in to the Mac desktop before installing the LaunchAgent.'
mode=launchd
elif [ "$force_cron" = false ] && [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then
systemctl show-environment >/dev/null 2>&1 || fail 'Cannot reach systemd. Use --cron to select user cron.'
mode=systemd
fi
root() {
if [ "$(id -u)" = 0 ]; then "$@"; else sudo "$@"; fi
}
directory=$HOME/.local/share/turnit-heartbeat/$identity
unit=/etc/systemd/system/$key.service
plist=$HOME/Library/LaunchAgents/$label.plist
if [ "$mode" = systemd ]; then
directory=/etc/turnit-heartbeat/$identity
if [ "$(id -u)" != 0 ]; then
command -v sudo >/dev/null 2>&1 || fail 'Systemd installation needs sudo. Alternatively, use --cron.'
printf '%s\n' 'TurnIt needs sudo to manage this device system service.'
sudo -v || fail 'Sudo authorization failed.'
fi
elif [ "$mode" = cron ]; then
command -v crontab >/dev/null 2>&1 || fail 'crontab is required when systemd is unavailable.'
fi
stage=$(mktemp -d "${TMPDIR:-/tmp}/turnit-install.XXXXXXXX")
trap 'rm -rf "$stage"' 0
trap 'exit 1' HUP INT TERM
read_cron() {
if LC_ALL=C crontab -l >"$stage/cron" 2>"$stage/cron-error"; then return; fi
# An empty crontab is normal; permission errors must not overwrite existing jobs.
if LC_ALL=C grep -qi 'no crontab for' "$stage/cron-error"; then
: >"$stage/cron"
else
fail 'Cannot read the current crontab. Check cron permissions.'
fi
}
filter_cron() {
awk -v marker="# $key" '!(length($0) >= length(marker) && substr($0, length($0)-length(marker)+1) == marker)' "$stage/cron" >"$stage/cron-new"
}
stop_runner() {
[ -f "$directory/lock/pid" ] || return 0
pid=$(cat "$directory/lock/pid")
case "$pid" in ''|*[!0-9]*) fail 'Invalid heartbeat process ID.' ;; esac
[ "$pid" -gt 1 ] || fail 'Invalid heartbeat process ID.'
if kill -0 "$pid" 2>/dev/null; then
process=$(ps -ww -p "$pid" -o args=) || return 0
owner_script=$(cat "$directory/lock/script" 2>/dev/null || printf '%s' "$directory/heartbeat.sh")
case "$process" in
*"/bin/sh $owner_script"*) kill "$pid" ;;
*) return 0 ;;
esac
count=0
while kill -0 "$pid" 2>/dev/null && [ "$count" -lt 10 ]; do sleep 1; count=$((count + 1)); done
kill -0 "$pid" 2>/dev/null && fail 'The heartbeat process did not stop.'
fi
return 0
}
# Preflight dependencies before stopping an existing installation.
if [ "$uninstall" = false ]; then
curl_path=$(command -v curl) || fail 'curl is required. Install it before running this installer.'
case "$curl_path" in /*) ;; *) fail 'curl must be an executable on PATH.' ;; esac
if [ "$mode" = systemd ]; then curl_path=/usr/bin/curl; [ -x "$curl_path" ] || fail 'Systemd installation requires /usr/bin/curl.'; fi
fi
case "$mode" in
systemd)
if root systemctl is-active --quiet "$key.service"; then root systemctl stop "$key.service"; fi ;;
launchd)
if launchctl print "gui/$(id -u)/$label" >/dev/null 2>&1; then launchctl bootout "gui/$(id -u)/$label"; fi ;;
cron)
read_cron
filter_cron
crontab "$stage/cron-new"
stop_runner ;;
esac
if [ "$uninstall" = true ]; then
case "$mode" in
systemd)
if [ -f "$unit" ]; then root systemctl disable "$key.service"; root rm -f "$unit"; root systemctl daemon-reload; fi
root rm -rf "$directory" ;;
launchd) rm -f "$plist"; rm -rf "$directory" ;;
cron) rm -rf "$directory" ;;
esac
printf '%s\n' "Removed TurnIt heartbeat for device $identity ($mode)."
exit 0
fi
printf 'url = "%s"\n' "$endpoint" >"$stage/request.conf"
printf '%s\n' "$interval" >"$stage/interval"
printf '%s\n' "$curl_path" >"$stage/curl-path"
cat >"$stage/heartbeat.sh" <<'RUNNER'
#!/bin/sh
set -eu
umask 077
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
export PATH
directory=$(CDPATH= cd -P "$(dirname "$0")" && pwd)
interval=$(cat "$directory/interval")
curl_path=$(cat "$directory/curl-path")
once=false
[ "${1:-}" != --once ] || once=true
child=
cleanup() {
[ -z "$child" ] || kill "$child" 2>/dev/null || :
rm -rf "$directory/lock"
}
if ! mkdir "$directory/lock" 2>/dev/null; then
# Allow an acquiring process to write its PID before checking for a stale lock.
sleep 1
pid=$(cat "$directory/lock/pid" 2>/dev/null || :)
case "$pid" in ''|*[!0-9]*) pid=0 ;; esac
if [ "$pid" -gt 1 ] && kill -0 "$pid" 2>/dev/null; then
process=$(ps -ww -p "$pid" -o args= 2>/dev/null || :)
owner_script=$(cat "$directory/lock/script" 2>/dev/null || printf '%s' "$directory/heartbeat.sh")
case "$process" in *"/bin/sh $owner_script"*)
printf '%s\n' 'A heartbeat process already owns the lock.' >&2
exit 1 ;;
esac
fi
rm -rf "$directory/lock"
mkdir "$directory/lock" 2>/dev/null || exit 1
fi
trap cleanup 0
trap 'exit 0' HUP INT TERM
printf '%s\n' "$0" >"$directory/lock/script"
printf '%s\n' "$$" >"$directory/lock/pid"
pause() {
sleep "$1" & child=$!
wait "$child" || :
child=
}
attempt=0
while :; do
now=$(date +%s)
next=$(cat "$directory/next-at" 2>/dev/null || printf 0)
case "$next" in ''|*[!0-9]*) next=0 ;; esac
# Bound stale deadlines after a system clock change.
if [ "$next" -gt "$now" ]; then
delay=$((next - now))
[ "$delay" -le 86400 ] || delay=$interval
if [ "$once" = true ]; then printf 'Waiting %s seconds before the first heartbeat.\n' "$delay"; fi
pause "$delay"
fi
status_file=$directory/lock/status
"$curl_path" --silent --globoff --proto '=http,https' --max-time 5 --connect-timeout 5 \
--config "$directory/request.conf" --output /dev/null \
--dump-header "$directory/lock/headers" --write-out '%{http_code}' >"$status_file" 2>/dev/null & child=$!
result=0
wait "$child" || result=$?
child=
status=$(cat "$status_file")
delay=$interval
accepted=false
if [ "$result" = 0 ]; then
case "$status" in
2??) accepted=true ;;
429)
retry=$(awk 'tolower($1) == "retry-after:" {gsub("\r", "", $2); print $2; exit}' "$directory/lock/headers")
case "$retry" in ''|*[!0-9]*|0*) ;; *)
if [ "${#retry}" -le 5 ] && [ "$retry" -le 86400 ]; then delay=$retry; fi ;;
esac ;;
esac
fi
printf '%s\n' "$(($(date +%s) + delay))" >"$directory/next-at"
if [ "$accepted" = true ]; then
if [ "$once" = true ]; then exit 0; fi
else
printf 'Heartbeat not accepted (HTTP %s, curl %s); retry in %s seconds.\n' "$status" "$result" "$delay" >&2
if [ "$once" = true ]; then
# Retry a rate-limited installation once, respecting Retry-After.
if [ "$status" != 429 ] || [ "$attempt" -ge 1 ]; then exit 1; fi
attempt=$((attempt + 1))
fi
fi
done
RUNNER
if [ "$mode" = systemd ]; then
root install -d -m 700 "$directory"
for file in heartbeat.sh request.conf interval curl-path; do root install -m 600 "$stage/$file" "$directory/$file"; done
else
mkdir -p "$directory"
chmod 700 "$directory"
for file in heartbeat.sh request.conf interval curl-path; do cp "$stage/$file" "$directory/$file"; chmod 600 "$directory/$file"; done
fi
probe=0
if [ "$mode" = systemd ]; then
root /bin/sh "$directory/heartbeat.sh" --once || probe=$?
else
/bin/sh "$directory/heartbeat.sh" --once || probe=$?
fi
case "$mode" in
systemd)
cat >"$stage/service" </\>/g; s/"/\"/g')
cat >"$plist" <
Label$label
ProgramArguments/bin/sh$xml_path
RunAtLoad
KeepAlive
ThrottleInterval5
PLIST
chmod 600 "$plist"
launchctl enable "gui/$(id -u)/$label"
launchctl bootstrap "gui/$(id -u)" "$plist"
launchctl print "gui/$(id -u)/$label" >/dev/null || fail 'The LaunchAgent did not load.' ;;
cron)
# Escape shell quotes first, then cron's special percent syntax.
quoted_path=$(printf '%s' "$directory/heartbeat.sh" | sed "s/'/'\\\\''/g; s/%/\\\\%/g")
printf "@reboot /bin/sh '%s' >/dev/null 2>/dev/null # %s\n" "$quoted_path" "$key" >>"$stage/cron-new"
crontab "$stage/cron-new"
nohup /bin/sh "$directory/heartbeat.sh" >/dev/null 2>/dev/null &
runner_pid=$!
sleep 1
kill -0 "$runner_pid" 2>/dev/null || fail 'The heartbeat process did not start.' ;;
esac
printf 'Installed TurnIt heartbeat for device %s (%s), every %s seconds.\n' "$identity" "$mode" "$interval"
printf '%s\n' 'To remove it, run the Uninstall command from this device guide with the same user and mode.'
if [ "$probe" != 0 ]; then
fail 'Installed, but the first heartbeat could not be confirmed. The background process will retry; check the device dashboard.'
fi
printf '%s\n' 'First heartbeat accepted. Check Last heartbeat in your TurnIt dashboard.'