Files
kvitt/infra/pi/lib.sh
T

69 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
# Shared helpers for the Kvitt Pi scripts (install.sh, deploy.sh, bootstrap.sh, backup-now.sh, install-apk.sh).
# Sourced, not run. These scripts run ON the Kvitt Pi as the owner's user (a member of the docker group).
# shellcheck disable=SC2034 # variables are used by the scripts that source this file
KVITT_DIR=${KVITT_DIR:-/opt/kvitt}
PUBLIC_HOST=icehack.asuscomm.com
PUBLIC_PORT=8443
say() { printf '%s\n' "$*"; }
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
# Value of KEY in an env file (default /opt/kvitt/.env); empty when unset.
env_value() {
local file=${2:-$KVITT_DIR/.env}
sed -n "s/^$1=//p" "$file" | tail -n 1
}
# Set KEY=VALUE in an env file in place (adds the line when missing). Keeps the file's mode.
env_set() {
local key=$1 value=$2 file=${3:-$KVITT_DIR/.env} tmp
tmp=$(mktemp "$file.XXXXXX")
if grep -q "^$key=" "$file"; then
awk -v k="$key" -v v="$value" 'index($0, k "=") == 1 { print k "=" v; next } { print }' "$file" > "$tmp" \
|| { rm -f "$tmp"; return 1; }
else
{ cat "$file" && printf '%s=%s\n' "$key" "$value"; } > "$tmp" || { rm -f "$tmp"; return 1; }
fi
if ! { chmod --reference="$file" "$tmp" && mv -f "$tmp" "$file"; }; then rm -f "$tmp"; return 1; fi
}
compose() {
docker compose --project-directory "$KVITT_DIR" -f "$KVITT_DIR/compose.yaml" --env-file "$KVITT_DIR/.env" "$@"
}
# Health status of a compose service's container: healthy, unhealthy, starting, or none.
service_health() {
local id
id=$(compose ps -q "$1" 2>/dev/null | head -n 1)
[[ -n "$id" ]] || { echo none; return; }
docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$id" 2>/dev/null || echo none
}
# Wait until a service is healthy (default 180 s). Returns 1 on timeout.
wait_healthy() {
local service=$1 timeout=${2:-180} waited=0 status
while :; do
status=$(service_health "$service")
[[ "$status" == healthy ]] && { say "$service: healthy"; return 0; }
if (( waited >= timeout )); then
say "$service: $status after ${timeout}s"
return 1
fi
sleep 5
waited=$((waited + 5))
done
}
# GET /health through Caddy on this Pi, with the real certificate check (no -k): proves TLS and the proxy path.
print_health() {
local out
if out=$(curl -fsS --max-time 15 --resolve "$PUBLIC_HOST:$PUBLIC_PORT:127.0.0.1" "https://$PUBLIC_HOST:$PUBLIC_PORT/health" 2>&1); then
say "GET https://$PUBLIC_HOST:$PUBLIC_PORT/health (via this Pi): $out"
return 0
fi
say "GET https://$PUBLIC_HOST:$PUBLIC_PORT/health (via this Pi) failed: $out"
return 1
}