4 GEOIPDB=http://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip
9 echo Usage: ${0##*/} [options]
12 echo " " -h display this help message
13 echo " " -s be more silent \(show only warnings\)
18 args=`getopt -o sh -l silent,help -- "$@"`
22 -h|--help) usage; exit 0 ;;
23 -s|--silent) SILENT="1"; shift ;;
25 *) echo "Invalid option: $1"; exit 1 ;;
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'
34 psql --set "ON_ERROR_STOP=1" -f - <<EOF
37 DROP TABLE IF EXISTS geoip CASCADE;
39 id SERIAL PRIMARY KEY,
45 DROP FUNCTION IF EXISTS inet_to_bigint(INET);
46 CREATE OR REPLACE FUNCTION inet_to_bigint(ip INET)
56 sp := regexp_split_to_array(ip::text, E'\\\\.');
60 z := substring(sp[4], 0, strpos(sp[4], '/'));
61 return 16777216*w::bigint + 65536*x::bigint + 256*y::bigint + z::bigint;
63 \$\$ LANGUAGE plpgsql IMMUTABLE;
70 trap "rm -rf $DIR;" EXIT
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 ?
79 unzip ${GEOIPDB##*/} $GEOIPCVS
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;"