#!/bin/bash
LOG_FILE="/tmp/notify-ip.log"
BARK_TITLE="北京 daheng 内网 IP 报告"
BARK_GROUP="Server IP 提醒"
RETRY_COUNT=0
MAX_RETRIES=60
BARK_PUSH_URL=""
BARK_DEVICE_KEY=""
log() {
local level="$1"
shift
printf '%s [%s] %s\n' "$(date '+%Y-%m-%dT%H:%M:%S%z')" "$level" "$*" >> "$LOG_FILE"
}
MISSING_CONFIG=()
if [ -z "${BARK_PUSH_URL:-}" ]; then
MISSING_CONFIG+=("BARK_PUSH_URL")
fi
if [ -z "${BARK_DEVICE_KEY:-}" ]; then
MISSING_CONFIG+=("BARK_DEVICE_KEY")
fi
if [ "${#MISSING_CONFIG[@]}" -gt 0 ]; then
log ERROR "Missing required Bark config: ${MISSING_CONFIG[*]}"
exit 1
fi
if ! command -v python3 > /dev/null 2>&1; then
log ERROR "python3 is required to build the Bark payload"
exit 1
fi
if ! command -v curl > /dev/null 2>&1; then
log ERROR "curl is required to send the Bark notification"
exit 1
fi
log INFO "Waiting for network connectivity; max retries: ${MAX_RETRIES}"
while ! ping -c 1 -W 1 8.8.8.8 > /dev/null 2>&1; do
RETRY_COUNT=$((RETRY_COUNT + 1))
if [ "$RETRY_COUNT" -ge "$MAX_RETRIES" ]; then
log ERROR "Network timeout after ${MAX_RETRIES} attempts, exiting"
exit 1
fi
if [ $((RETRY_COUNT % 10)) -eq 0 ]; then
log INFO "Network still unavailable after ${RETRY_COUNT} attempts"
fi
sleep 1
done
log INFO "Network connectivity confirmed after ${RETRY_COUNT} attempts"
INTERNAL_IPS=$(ip -4 addr show | awk '/ inet / { split($2, ip, "/"); if (ip[1] !~ /^127\./) print ip[1] }')
if [ -z "$INTERNAL_IPS" ]; then
MESSAGE="无法获取内网 IP 地址。"
else
MESSAGE="主机内网 IP 地址:$(printf '%s\n' "$INTERNAL_IPS" | tr '\n' ' ')"
fi
JSON_PAYLOAD=$(
BARK_TITLE="$BARK_TITLE" \
BARK_BODY="$MESSAGE" \
BARK_DEVICE_KEY="$BARK_DEVICE_KEY" \
BARK_GROUP="$BARK_GROUP" \
python3 - <<'PY'
import json
import os
payload = {
"title": os.environ["BARK_TITLE"],
"body": os.environ["BARK_BODY"],
"device_key": os.environ["BARK_DEVICE_KEY"],
"group": os.environ["BARK_GROUP"],
}
print(json.dumps(payload, ensure_ascii=False))
PY
)
RESPONSE_FILE=$(mktemp)
log INFO "Sending Bark notification"
HTTP_STATUS=$(
curl -sS -o "$RESPONSE_FILE" -w '%{http_code}' \
-X POST "$BARK_PUSH_URL" \
-H 'Content-Type: application/json; charset=utf-8' \
--data-binary "$JSON_PAYLOAD" 2>> "$LOG_FILE"
)
CURL_EXIT=$?
RESPONSE_BODY=$(cat "$RESPONSE_FILE")
rm -f "$RESPONSE_FILE"
log INFO "Bark HTTP status: ${HTTP_STATUS:-unknown}"
log INFO "Bark response body: ${RESPONSE_BODY:-<empty>}"
if [ "$CURL_EXIT" -ne 0 ]; then
log ERROR "Bark notification failed with curl exit code ${CURL_EXIT}"
exit "$CURL_EXIT"
fi
case "$HTTP_STATUS" in
2*)
log INFO "Bark notification sent successfully"
;;
*)
log ERROR "Bark notification returned non-success HTTP status: ${HTTP_STATUS:-unknown}"
exit 1
;;
esac
echo "Attempted to send Bark notification."