]> dev.renevier.net Git - syj.git/blob - scripts/updategeonames.sh
version 0.1
[syj.git] / scripts / updategeonames.sh
1 #!/bin/sh
2 set -e
3
4 GEONAMESXML=http://ws.geonames.org/countryInfo
5
6 EXECDIR=$PWD/${0%/*}
7 . $EXECDIR/db_auth.sh
8
9 usage() {
10     echo Usage: ${0##*/} [options]
11     echo
12     echo Options:
13     echo "  " -h display this help message
14     echo "  " -s be more silent \(show only warnings\)
15 }
16
17 # getopt
18 SILENT=""
19 args=`getopt -o sh -l silent,help -- "$@"`
20 eval set -- "$args"
21 while true; do
22     case "$1" in
23         -h|--help) usage; exit 0 ;;
24         -s|--silent) SILENT="1"; shift ;;
25         --) shift; break ;;
26         *) echo "Invalid option: $1"; exit 1 ;;
27     esac
28 done
29
30 if [ ${#SILENT} -ne 0 ]; then
31     # we won't see all the index creation notices when creating tables
32     export PGOPTIONS='--client_min_messages=warning'
33 fi
34
35 psql --set "ON_ERROR_STOP=1" -f - <<EOF
36 BEGIN;
37 DROP TABLE IF EXISTS geonames CASCADE;
38 CREATE TABLE geonames (
39     country CHAR(2) UNIQUE PRIMARY KEY,
40     minlon real,
41     minlat real,
42     maxlon real,
43     maxlat real
44 );
45 COMMIT;
46 EOF
47
48 TMPDIR=`mktemp -d`
49 TMPFILE=`mktemp --tmpdir=$TMPDIR`
50 trap "rm -rf $TMPDIR;" EXIT
51 cd $TMPDIR
52 wget $GEONAMESXML
53
54 for line in $(cat ${GEONAMESXML##*/}); do
55     if echo $line | grep -qi '<country>'; then
56         COUNTRY=""; MINLON=""; MINLAT=""; MAXLON=""; MAXLAT=""
57     elif echo $line | grep -qi '<countryCode>.*</countryCode>'; then
58         COUNTRY=$(echo $line | sed -e 's/^\s*<countryCode>\(.*\)<\/countryCode>\s*/\1/i')
59     elif echo $line | grep -qi '<bBoxWest>.*</bBoxWest>'; then
60         MINLON=$(echo $line | sed -e 's/^\s*<bBoxWest>\(.*\)<\/bBoxWest>\s*/\1/i')
61     elif echo $line | grep -qi '<bBoxSouth>.*</bBoxSouth>'; then
62         MINLAT=$(echo $line | sed -e 's/^\s*<bBoxSouth>\(.*\)<\/bBoxSouth>\s*/\1/i')
63     elif echo $line | grep -qi '<bBoxEast>.*</bBoxEast>'; then
64         MAXLON=$(echo $line | sed -e 's/^\s*<bBoxEast>\(.*\)<\/bBoxEast>\s*/\1/i')
65     elif echo $line | grep -qi '<bBoxNorth>.*</bBoxNorth>'; then
66         MAXLAT=$(echo $line | sed -e 's/^\s*<bBoxNorth>\(.*\)<\/bBoxNorth>\s*/\1/i')
67     elif echo $line | grep -qi '<\/country>'; then
68         if [ ${#COUNTRY} -ne 0 -a ${#MINLON} -ne 0 -a ${#MINLAT} -ne 0 -a ${#MAXLON} -ne 0 -a ${#MAXLAT} -ne 0 ]; then
69             echo "INSERT INTO geonames (country, minlon, minlat, maxlon, maxlat) VALUES ('$COUNTRY', $MINLON, $MINLAT, $MAXLON, $MAXLAT);" >> $TMPFILE
70         fi
71     fi
72 done
73 echo "INSERT INTO geonames (country, minlon, minlat, maxlon, maxlat) VALUES ('EU', -26, 34, 40, 68);" >> $TMPFILE
74 echo "INSERT INTO geonames (country, minlon, minlat, maxlon, maxlat) VALUES ('AP', 90, -20, -140, 68);" >> $TMPFILE
75 psql --set "ON_ERROR_STOP=1" -f $TMPFILE