]> dev.renevier.net Git - syj.git/blob - scripts/updategeoip.sh
make installation process more simple
[syj.git] / scripts / updategeoip.sh
1 #!/bin/sh
2 set -e
3
4 GEOIPDB=http://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip
5
6 . ${0%/*}/db_auth.sh
7
8 usage() {
9     echo Usage: ${0##*/} [options]
10     echo
11     echo Options:
12     echo "  " -h display this help message
13     echo "  " -s be more silent \(show only warnings\)
14 }
15
16 # getopt
17 SILENT=""
18 args=`getopt -o sh -l silent,help -- "$@"`
19 eval set -- "$args"
20 while true; do
21     case "$1" in
22         -h|--help) usage; exit 0 ;;
23         -s|--silent) SILENT="1"; shift ;;
24         --) shift; break ;;
25         *) echo "Invalid option: $1"; exit 1 ;;
26     esac
27 done
28
29 if [ ${#SILENT} -ne 0 ]; then
30     # we won't see all the index creation notices when creating tables
31     export PGOPTIONS='--client_min_messages=warning'
32 fi
33
34 psql --set "ON_ERROR_STOP=1" -f - <<EOF
35 BEGIN;
36
37 DROP TABLE IF EXISTS geoip CASCADE;
38 CREATE TABLE geoip (
39     id SERIAL PRIMARY KEY,
40     begin_ip BIGINT,
41     end_ip BIGINT,
42     country CHAR(2)
43 );
44
45 DROP FUNCTION IF EXISTS inet_to_bigint(INET);
46 CREATE OR REPLACE FUNCTION inet_to_bigint(ip INET)
47     RETURNS BIGINT AS
48 \$\$
49 DECLARE
50     w TEXT;
51     x TEXT;
52     y TEXT;
53     z TEXT;
54     sp TEXT[];
55 BEGIN
56     sp := regexp_split_to_array(ip::text, E'\\\\.');
57     w := sp[1];
58     x := sp[2];
59     y := sp[3];
60     z := substring(sp[4], 0, strpos(sp[4], '/'));
61     return 16777216*w::bigint + 65536*x::bigint + 256*y::bigint + z::bigint;
62 END;
63 \$\$ LANGUAGE plpgsql IMMUTABLE;
64
65 COMMIT;
66 EOF
67
68
69 DIR=`mktemp -d`
70 trap "rm -rf $DIR;" EXIT
71 cd $DIR
72 wget $GEOIPDB
73 GEOIPCVS=$(zipinfo -1 ${GEOIPDB##*/} | grep '\.csv$')
74 if [ $(echo $GEOIPCVS | wc -w) -lt "1" ]; then
75     echo There is no csv file in the archive. Canceling
76 elif [ $(echo $GEOIPCVS | wc -w) -gt "1" ]; then
77     echo There is more than one csv file in the archive. Which one should I pick ?
78 fi
79 unzip ${GEOIPDB##*/} $GEOIPCVS
80
81 # insert all values from csv to database
82 sed -e 's/"\([^"]\+\)","\([^"]\+\)","\([^"]\+\)","\([^"]\+\)","\([^"]\+\)","\([^"]\+\)"/INSERT INTO geoip (begin_ip, end_ip, country) VALUES ('\''\3'\'','\''\4'\'','\''\5'\'');/' $GEOIPCVS | psql --set "ON_ERROR_STOP=1" -f -
83 psql --set "ON_ERROR_STOP=1" -c "VACUUM ANALYZE geoip;"