Files
RadioPropagationApi/scripts/load_buildings.sh
T
2026-06-23 09:57:39 +03:00

87 lines
2.3 KiB
Bash

#!/usr/bin/env sh
set -eu
if [ "${1:-}" = "" ]; then
echo "Usage: $0 path/to/osm.pbf" >&2
exit 2
fi
PBF_PATH=$1
if [ ! -f "$PBF_PATH" ]; then
echo "OSM PBF file not found: $PBF_PATH" >&2
exit 2
fi
if [ -f .env ]; then
set -a
# shellcheck disable=SC1091
. ./.env
set +a
fi
DB_NAME=${POSTGRES_DB:-radio}
DB_USER=${POSTGRES_USER:-radio}
DB_PASSWORD=${DB_PASSWORD:-radio}
POSTGIS_SERVICE=${POSTGIS_SERVICE:-postgis}
OSM2PGSQL_IMAGE=${OSM2PGSQL_IMAGE:-radio-osm2pgsql:latest}
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
REPO_DIR=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)
PBF_DIR=$(CDPATH= cd -- "$(dirname -- "$PBF_PATH")" && pwd)
PBF_FILE=$(basename -- "$PBF_PATH")
POSTGIS_CONTAINER=$(docker compose ps -q "$POSTGIS_SERVICE")
if [ -z "$POSTGIS_CONTAINER" ]; then
echo "PostGIS container is not running. Start it with: docker compose up -d postgis" >&2
exit 1
fi
NETWORK=$(docker inspect "$POSTGIS_CONTAINER" \
--format '{{range $name, $_ := .NetworkSettings.Networks}}{{println $name}}{{end}}' \
| head -n 1)
if ! docker image inspect "$OSM2PGSQL_IMAGE" >/dev/null 2>&1; then
echo "Build local osm2pgsql image: $OSM2PGSQL_IMAGE"
docker build \
-t "$OSM2PGSQL_IMAGE" \
-f "$SCRIPT_DIR/Dockerfile.osm2pgsql" \
"$SCRIPT_DIR"
fi
echo "Ensure PostGIS extension exists"
docker compose exec -T "$POSTGIS_SERVICE" psql -U "$DB_USER" -d "$DB_NAME" \
< "$REPO_DIR/db/init/01_postgis.sql"
echo "Drop previous buildings table"
docker compose exec -T "$POSTGIS_SERVICE" psql -U "$DB_USER" -d "$DB_NAME" \
-c "DROP TABLE IF EXISTS buildings CASCADE;"
echo "Import buildings from $PBF_PATH"
docker run --rm \
--network "$NETWORK" \
-e PGPASSWORD="$DB_PASSWORD" \
-v "$PBF_DIR:/osm:ro" \
-v "$SCRIPT_DIR:/scripts:ro" \
"$OSM2PGSQL_IMAGE" \
-H "$POSTGIS_SERVICE" \
-P 5432 \
-U "$DB_USER" \
-d "$DB_NAME" \
--create \
--slim \
--drop \
--latlong \
--output flex \
--style /scripts/osm2pgsql_buildings.lua \
"/osm/$PBF_FILE"
echo "Create buildings indexes"
docker compose exec -T "$POSTGIS_SERVICE" psql -U "$DB_USER" -d "$DB_NAME" <<'SQL'
CREATE INDEX IF NOT EXISTS buildings_geom_gix ON buildings USING GIST (geom);
CREATE INDEX IF NOT EXISTS buildings_height_idx ON buildings (height_m);
CREATE INDEX IF NOT EXISTS buildings_type_idx ON buildings (building_type);
ANALYZE buildings;
SQL
echo "Buildings import complete"