diff --git a/scripts/fetch-year.sh b/scripts/fetch-year.sh new file mode 100755 index 0000000..c79d1b6 --- /dev/null +++ b/scripts/fetch-year.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# Usage: ./scripts/fetch-year.sh YEAR +# Fetches sequentially; prints JSON responses to stdout and errors to stderr. +set -euo pipefail + +if [[ $# -ne 1 ]]; then + echo "Usage: $0 YEAR" >&2 + exit 1 +fi + +year=$1 +if [[ ! $year =~ ^[0-9]{4}$ || $year == 0000 ]]; then + echo "YEAR must be a four-digit year from 0001 to 9999." >&2 + exit 1 +fi + +year_number=$((10#$year)) +days_in_month=(31 28 31 30 31 30 31 31 30 31 30 31) +if (( year_number % 400 == 0 || (year_number % 4 == 0 && year_number % 100 != 0) )); then + days_in_month[1]=29 +fi + +# Reuse a reachable service, or keep a port-forward alive while fetching. +service_ready() { + curl --fail --silent --output /dev/null --connect-timeout 1 --max-time 2 \ + 'http://localhost:4101/api/health' +} + +forward_pid= +cleanup() { + if [[ -n $forward_pid ]]; then + kill "$forward_pid" 2>/dev/null || true + wait "$forward_pid" 2>/dev/null || true + fi +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +if ! service_ready; then + if ! command -v kubectl >/dev/null 2>&1; then + echo "Service unavailable on localhost:4101 and kubectl is not installed." >&2 + exit 1 + fi + echo "Starting kubectl port-forward for sejs/btcdata..." >&2 + kubectl -n sejs port-forward svc/btcdata 4101:4101 >&2 & + forward_pid=$! + + ready=false + for (( attempt = 0; attempt < 30; attempt++ )); do + if ! kill -0 "$forward_pid" 2>/dev/null; then + echo "Port-forward exited before the service became ready." >&2 + exit 1 + fi + if service_ready; then + ready=true + break + fi + sleep 1 + done + if [[ $ready != true ]]; then + echo "Timed out waiting for the service on localhost:4101." >&2 + exit 1 + fi +fi + +# Generate dates without relying on platform-specific date command options. +status=0 +for (( month = 1; month <= 12; month++ )); do + for (( day = 1; day <= days_in_month[month - 1]; day++ )); do + printf -v date '%s-%02d-%02d' "$year" "$month" "$day" + if ! curl --fail --silent --show-error -X GET \ + "http://localhost:4101/api/price/day/$date" \ + -H "accept: application/json" --write-out '\n'; then + echo "Failed to fetch $date" >&2 + status=1 + fi + done +done +exit "$status"