#!/bin/bash ## ## Download Virginia's 2026 general election results plus the Census data ## used to describe each precinct and county. ## ROOT=$(cd "$(dirname "$(realpath "${BASH_SOURCE[0]}")")/.." && pwd) DATA=$ROOT/data ENR=https://enr.elections.virginia.gov ELECTION=2026-November-General OP_PROFILE=iiifff OP_ITEM="api.census.gov API key" mkdir -p "$DATA" usage() { echo "Usage: $(basename $0) [-E] [-C]" echo " -E election files only" echo " -C census files only" exit 1 } while getopts "ECh" o; do case "$o" in E) only=election ;; C) only=census ;; *) usage ;; esac done fetch_report() { local name="$1" out="$2" jurisdiction blob jurisdiction=$(jq -r .jurisdictionId "$DATA/election.json") blob=$(jq -r --arg n "$name" '.publicReportCategories[].reports[]? | select(.reportName == $n) | .blobName' "$DATA/election.json" | head -1) if [ -z "$blob" ]; then echo "No '$name' report in the current publish; keeping the previous copy" >&2 return 1 fi if curl -sf -o "$out.tmp" "$ENR/cdn/results/$jurisdiction/${blob// /%20}"; then mv "$out.tmp" "$out" echo "$name -> $out" else rm -f "$out.tmp" echo "Failed to download $name ($blob)" >&2 return 1 fi } fetch_election() { curl -sf -o "$DATA/election.json" "$ENR/results/public/api/elections/virginia/$ELECTION" || { echo "Can't reach the ENR election record" >&2; exit 1 } echo "Publish: $(jq -r .lastUpdated "$DATA/election.json")" fetch_report "Election Results" "$DATA/results.csv" && jq -r .lastUpdated "$DATA/election.json" > "$DATA/publish.txt" fetch_report "Election Turnout" "$DATA/turnout.csv" fetch_report "EnrAbsenteeRawCSV" "$DATA/absentee.csv" } fetch_census() { local key key=$(opassist -a password -p "$OP_PROFILE" -n "$OP_ITEM" 2>/dev/null) if [ -z "$key" ]; then echo "No Census key: 1Password item '$OP_ITEM'. If locked: opassist -a signin" >&2 exit 1 fi curl -sf -o "$DATA/census-vtd.json" \ "https://api.census.gov/data/2020/dec/pl?get=NAME,P4_001N,P4_002N,P4_005N,P4_006N,P4_008N&for=voting%20district:*&in=state:51&in=county:*&key=$key" \ && echo "2020 Census race by voting district -> $DATA/census-vtd.json" curl -sf -o "$DATA/census-county.json" \ "https://api.census.gov/data/2023/acs/acs5?get=NAME,B19013_001E&for=county:*&in=state:51&key=$key" \ && echo "ACS 2019-2023 median household income -> $DATA/census-county.json" } [ "$only" != census ] && fetch_election [ "$only" != election ] && fetch_census exit 0