#!/bin/sh

set -x

TMPDIR=`mktemp -d /tmp/geonames.XXXXXX`
CURDIR=`pwd`

# optionally specify minimum city population size with POPULATION=750
POPULATION=${POPULATION:-"0"}

# optionally specify a geonames export file such as cities500 or cities5000
CITIES=${CITIES:-"cities1000"}

curl -o $TMPDIR/countryInfo.txt http://download.geonames.org/export/dump/countryInfo.txt
curl -o $TMPDIR/admin1CodesASCII.txt http://download.geonames.org/export/dump/admin1CodesASCII.txt
curl -o $TMPDIR/$CITIES.zip http://download.geonames.org/export/dump/$CITIES.zip
curl -o $TMPDIR/IL.zip http://download.geonames.org/export/dump/IL.zip
curl -o $TMPDIR/alt-IL.zip http://download.geonames.org/export/dump/alternatenames/IL.zip

cd $TMPDIR
unzip $CITIES.zip
unzip alt-IL.zip
mv IL.txt alt-IL.txt
rm readme.txt
unzip IL.zip

cd $CURDIR

#npx --package '@hebcal/geo-sqlite' build-geonames-sqlite \
$CURDIR/node_modules/.bin/build-geonames-sqlite \
  --population=$POPULATION \
  $CURDIR/geonames.sqlite3 \
  $TMPDIR/countryInfo.txt \
  "$TMPDIR/$CITIES.txt" \
  "$CURDIR/node_modules/@hebcal/geo-sqlite/cities-patch.txt" \
  $TMPDIR/admin1CodesASCII.txt \
  $TMPDIR/IL.txt \
  $TMPDIR/alt-IL.txt

rm -rf $TMPDIR

$CURDIR/node_modules/.bin/make-zips-sqlite \
  $CURDIR/zips.sqlite3 \
  "$CURDIR/node_modules/@hebcal/geo-sqlite/zips-dummy.sql"

ls -lh geonames.sqlite3 zips.sqlite3
