68 lines
1.5 KiB
Bash
68 lines
1.5 KiB
Bash
#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
|
|
log() { echo "[$(date -Is)] $*" >&2; }
|
|
|
|
sleep_until_next_rotate() {
|
|
local rotate_at="${ROTATE_AT:-03:00}"
|
|
local target_h target_m
|
|
IFS=: read -r target_h target_m <<<"$rotate_at"
|
|
target_h=$((10#$target_h))
|
|
target_m=$((10#$target_m))
|
|
|
|
local now_h now_m now_s target_s wait_s
|
|
now_h=$(date +%H)
|
|
now_m=$(date +%M)
|
|
now_h=$((10#$now_h))
|
|
now_m=$((10#$now_m))
|
|
now_s=$((now_h * 3600 + now_m * 60))
|
|
target_s=$((target_h * 3600 + target_m * 60))
|
|
|
|
if ((now_s < target_s)); then
|
|
wait_s=$((target_s - now_s))
|
|
else
|
|
wait_s=$((86400 - now_s + target_s))
|
|
fi
|
|
|
|
log "Next rotation at ${rotate_at} (${TZ:-UTC}) in ${wait_s}s"
|
|
sleep "$wait_s"
|
|
}
|
|
|
|
# Matches rotate.sh EXIT_RATE_LIMITED (EX_TEMPFAIL)
|
|
readonly EXIT_RATE_LIMITED=75
|
|
|
|
run_rotation() {
|
|
local reason="$1"
|
|
local wait_s="${RATE_LIMIT_WAIT_SECONDS:-3600}"
|
|
local rc
|
|
|
|
while true; do
|
|
log "$reason"
|
|
rc=0
|
|
/usr/local/bin/rotate.sh || rc=$?
|
|
case "$rc" in
|
|
0)
|
|
return 0
|
|
;;
|
|
"$EXIT_RATE_LIMITED")
|
|
log "PIA rate-limited (too many attempts); waiting ${wait_s}s before retry"
|
|
sleep "$wait_s"
|
|
reason="Retrying rotation after rate-limit wait"
|
|
;;
|
|
*)
|
|
>&2 echo "Rotation failed with exit code $rc"
|
|
return "$rc"
|
|
;;
|
|
esac
|
|
done
|
|
}
|
|
|
|
log "Starting gluetun PIA WireGuard rotator (TZ=${TZ:-UTC}, ROTATE_AT=${ROTATE_AT:-03:00})"
|
|
|
|
run_rotation "Running rotation on startup"
|
|
|
|
while true; do
|
|
sleep_until_next_rotate
|
|
run_rotation "Running scheduled daily rotation"
|
|
done
|