]> dev.renevier.net Git - syj.git/blob - scripts/updategeoip.sh
version 0.1
[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 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
38 DROP TABLE IF EXISTS geoip CASCADE;
39 CREATE TABLE geoip (
40     id SERIAL PRIMARY KEY,
41     begin_ip BIGINT,
42     end_ip BIGINT,
43     country CHAR(2)
44 );
45
46 DROP FUNCTION IF EXISTS inet_to_bigint(INET);
47 CREATE OR REPLACE FUNCTION inet_to_bigint(ip INET)
48     RETURNS BIGINT AS
49 \$\$
50 DECLARE
51     w TEXT;
52     x TEXT;
53     y TEXT;
54     z TEXT;
55     sp TEXT[];
56 BEGIN
57     sp := regexp_split_to_array(ip::text, E'\\\\.');
58     w := sp[1];
59     x := sp[2];
60     y := sp[3];
61     z := substring(sp[4], 0, strpos(sp[4], '/'));
62     return 16777216*w::bigint + 65536*x::bigint + 256*y::bigint + z::bigint;
63 END;
64 \$\$ LANGUAGE plpgsql IMMUTABLE;
65
66 COMMIT;
67 EOF
68
69
70 DIR=`mktemp -d`
71 trap "rm -rf $DIR;" EXIT
72 cd $DIR
73 wget $GEOIPDB
74 GEOIPCVS=$(zipinfo -1 ${GEOIPDB##*/} | grep '\.csv$')
75 if [ $(echo $GEOIPCVS | wc -w) -lt "1" ]; then
76     echo There is no csv file in the archive. Canceling
77 elif [ $(echo $GEOIPCVS | wc -w) -gt "1" ]; then
78     echo There is more than one csv file in the archive. Which one should I pick ?
79 fi
80 unzip ${GEOIPDB##*/} $GEOIPCVS
81
82 # insert all values from csv to database
83 sed -e 's/"\([^"]\+\)","\([^"]\+\)","\([^"]\+\)","\([^"]\+\)","\([^"]\+\)","\([^"]\+\)"/INSERT INTO geoip (begin_ip, end_ip, country) VALUES ('\''\3'\'','\''\4'\'','\''\5'\'');/' $GEOIPCVS | psql --set "ON_ERROR_STOP=1" -f -