Project

General

Profile

1
#!/bin/bash
2

    
3
# Bash script to create a new postgis database and prep it with GADM
4
# data for geovalidation purposes.
5
#
6
# Basic workflow:
7
#  1. Create postgis-enabled template db
8
#  2. Create postgis-enabled db from the template
9
#  3. Create required tables in postgis-enabled db
10
#  4. Load gadm2 and geonames.org data into database
11
#
12
# For postgis installation see:
13
#   http://trac.osgeo.org/postgis/wiki/UsersWikiPostGIS20Ubuntu1204
14
#
15
# Jim Regetz
16
# NCEAS
17
# Created November 2012
18
#
19
# refactored and reorganized by
20
# Paul Sarando
21
# iPlant Collaborative
22
# Updated Oct 2013
23

    
24
DB_NAME="geoscrub"
25
DB_USER="bien"
26
DB_HOST_OPT=""
27
SCRIPT_DIR="$(dirname $0)"
28

    
29
function run_sudo_sql_cmd {
30
    local SQL_CMD="$1"
31

    
32
    sudo -u postgres psql -e $DB_HOST_OPT -d "$DB_NAME" -c "$SQL_CMD"
33
    if [[ $? != 0 ]]; then
34
        echo "Error while executing SQL command."
35
        echo -n "You may drop the ${DB_NAME} database"
36
        echo " and attempt to run this $0 script again."
37
        exit 1
38
    fi
39
}
40

    
41
function run_sql_script {
42
    local SCRIPT="$1"
43

    
44
    psql -e --set ON_ERROR_STOP=1 -U "$DB_USER" $DB_HOST_OPT -d "$DB_NAME" < "$SCRIPT"
45
    if [[ $? != 0 ]]; then
46
        echo "Error while executing SQL script ${SCRIPT}"
47
        exit 1
48
    fi
49
}
50

    
51
# create postgis template if one doesn't already exist
52
echo "Setting up template_postgis database..."
53
sudo -u postgres createdb template_postgis
54
if [[ $? == 0 ]]; then
55
    # successfully created template_postgis, which means it didn't already exist
56
    sudo -u postgres psql -e -d template_postgis < "${SCRIPT_DIR}"/update.template_postgis.sql
57
    if [[ $? != 0 ]]; then
58
        echo "Could not create postgis extesion on template_postgis database."
59
        exit 1
60
    fi
61
fi
62

    
63
# create postgis db from template
64
echo "Creating the ${DB_NAME} database..."
65
createdb --no-password -U "$DB_USER" $DB_HOST_OPT "$DB_NAME" -T template_postgis
66
if [[ $? != 0 ]]; then
67
    echo "Could not create ${DB_NAME} database."
68
    exit 1
69
fi
70

    
71
echo "Updating ${DB_NAME} table permissions..."
72
run_sudo_sql_cmd "ALTER TABLE spatial_ref_sys OWNER TO ${DB_USER}"
73
run_sudo_sql_cmd "ALTER VIEW geography_columns OWNER TO ${DB_USER}"
74
run_sudo_sql_cmd "ALTER VIEW geometry_columns OWNER TO ${DB_USER}"
75

    
76
echo "Setting up ${DB_NAME} database tables..."
77
run_sql_script "${SCRIPT_DIR}"/setup.geonames.sql
78
run_sql_script "${SCRIPT_DIR}"/setup.geonames-to-gadm.sql
79
run_sql_script "${SCRIPT_DIR}"/setup.geoscrub.sql
80

    
81
echo "Install successfully completed."
82

    
(14-14/26)