#!/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" } log "Starting gluetun PIA WireGuard rotator (TZ=${TZ:-UTC}, ROTATE_AT=${ROTATE_AT:-03:00})" log "Running rotation on startup" /usr/local/bin/rotate.sh while true; do sleep_until_next_rotate log "Running scheduled daily rotation" /usr/local/bin/rotate.sh done