#! /bin/bash -ex
#################################################
# 
# Purpose: Patch TurnKey Linux LAPP 11.1 to fully configured Eden Appliance
# Based on: install_eden.sh for OSGeo LiveDVD
# Author:  Fran Boon, Rik Goldman, Steven Robinson, Jerel Moses, Maurice Quarles
#
#################################################
# Copyright (c) 2011 Open Source Geospatial Foundation (OSGeo)
#
# Licensed under the GNU LGPL.
# 
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 2.1 of the License,
# or any later version.  This library is distributed in the hope that
# it will be useful, but WITHOUT ANY WARRANTY, without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details, either
# in the "LICENSE.LGPL.txt" file distributed with this software or at
# web page "http://www.fsf.org/licenses/lgpl.html".
##################################################

#see also
# http://eden.sahanafoundation.org/wiki/InstallationGuidelinesLinux

# Check for Root User
gotroot=$(id -u)
if [[ ${gotroot} != "0" ]]; then
	echo -e "This script must run with root privileges."
	exit 100
fi

# Set Hostname
HOSTNAME=sahana-eden
echo "$HOSTNAME" > /etc/hostname
sed -i "s|127.0.1.1 \(.*\)|127.0.1.1 $HOSTNAME|" /etc/hosts

INSTALL_DIR="/usr/share"
SAHANA_CONF="/etc/apache2/sites-available/sahana"
BUILD_DIR=`pwd`
TMP_DIR="/tmp/build_sahana"
WEBSERVER="apache2"

if [ ! -d $TMP_DIR ]; then
	mkdir -p "$TMP_DIR"
fi

# Update from repos
apt-get update
# Install dependencies and support tools
DEBIAN_FRONTEND=noninteractive apt-get -y \
    -o DPkg::Options::=--force-confdef \
    -o DPkg::Options::=--force-confold \
    install \
	sudo \
	wget \
	bzip2 \
	make \
	g++ \
	zlib1g-dev \
	libgeos-c1 \
	bzr \
	python2.6 \
	python-dev \
	ipython \
	python-lxml \
	python-serial \
	python-setuptools \
	python-shapely \
	python-imaging \
	python-reportlab \
	python-xlwt \
	python-xlrd \
	libapache2-mod-wsgi \
	postgresql-8.4 \
	python-psycopg2 \
	postgresql-8.4-postgis

# Install python-tweepy
echo -e "deb http://ppa.launchpad.net/chris-lea/python-tweepy/ubuntu lucid main \n
deb-src http://ppa.launchpad.net/chris-lea/python-tweepy/ubuntu lucid main" >> /etc/apt/sources.list.d/sources.list
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C7917B12
apt-get update
apt-get install python-tweepy -y

#Download and Install Geraldo
#if [ ! -e "$TMP_DIR/Geraldo-0.4.10-stable.tar.gz" ]; then
#	wget http://pypi.python.org/packages/source/G/Geraldo/Geraldo-0.4.10-stable.tar.gz -O "$TMP_DIR/Geraldo-0.4-final.tar.gz"
#fi

#tar xvzf "$TMP_DIR"/Geraldo-0.4-final.tar.gz -C "$TMP_DIR"


#cd "$TMP_DIR"/Geraldo-0.4.10-final
#python setup.py install

# Add DB User
su -c - postgres "createuser -s sahana" && true
# Create Fresh DB
# ensure no active connections to old one
service apache2 stop
su -c - postgres "dropdb sahana" && true
su -c - postgres "createdb -O sahana sahana"
su -c - postgres "createlang plpgsql -d sahana"

# Add Role Password
if [ ! -e "$TMP_DIR/sahana.sql" ]; then
cat << EOF > "$TMP_DIR/sahana.sql"
ALTER ROLE sahana WITH PASSWORD 'sahana';
EOF
fi
su -c - postgres "psql -d sahana -f '$TMP_DIR/sahana.sql'"

# Import GIS template
su -c - postgres "psql -d sahana -f /usr/share/postgresql/8.4/contrib/postgis.sql"
su -c - postgres "psql -d sahana -f /usr/share/postgresql/8.4/contrib/spatial_ref_sys.sql"

# Add web2py account
adduser --system --disabled-password --no-create-home web2py && true
addgroup web2py && true
usermod -G web2py web2py && true

# Download web2py
rm -rf "$INSTALL_DIR"/web2py
#bzr branch -r 2922 lp:~mdipierro/web2py/devel "$INSTALL_DIR"/web2py 
wget -c http://eden.sahanafoundation.org/downloads/web2py_src-1.91.6.zip -O "$TMP_DIR/web2py_src-1.91.6.zip"
unzip "$TMP_DIR"/web2py_src-1.91.6.zip -d "$INSTALL_DIR"

# Cleanup web2py
rm "$TMP_DIR/web2py_src-1.91.6.zip"

#cp "$INSTALL_DIR"/web2py/routes.example.py "$INSTALL_DIR"/web2py/routes.py

# Install Sahana Eden
bzr branch lp:sahana-eden "$INSTALL_DIR/web2py/applications/eden"

# Create Eden Directories
mkdir -p "$INSTALL_DIR/web2py/applications/eden/uploads/gis_cache"
mkdir -p "$INSTALL_DIR/web2py/applications/eden/uploads/images"
mkdir -p "$INSTALL_DIR/web2py/applications/eden/uploads/tracks"
mkdir -p "$INSTALL_DIR/web2py/applications/eden/admin/cache"

# Set permissions
chown web2py:web2py \
	"$INSTALL_DIR/web2py/applications/admin/cache" \
	"$INSTALL_DIR/web2py" \
	"$INSTALL_DIR/web2py/applications/admin/cron" \
	"$INSTALL_DIR/web2py/applications/eden/cache" \
	"$INSTALL_DIR/web2py/applications/eden/cron" \
	"$INSTALL_DIR/web2py/applications/eden/databases" \
	"$INSTALL_DIR/web2py/applications/eden/errors" \
	"$INSTALL_DIR/web2py/applications/eden/models" \
	"$INSTALL_DIR/web2py/applications/eden/sessions" \
	"$INSTALL_DIR/web2py/applications/eden/static/img/markers" \
	"$INSTALL_DIR/web2py/applications/eden/uploads" \
	"$INSTALL_DIR/web2py/applications/eden/uploads/gis_cache" \
	"$INSTALL_DIR/web2py/applications/eden/uploads/images" \
	"$INSTALL_DIR/web2py/applications/eden/uploads/tracks"

# Copy Deployment Templates
if [ ! -f "$INSTALL_DIR/web2py/applications/eden/models" ]; then
	cp "$INSTALL_DIR/web2py/applications/eden/deployment-templates/models/000_config.py" "$INSTALL_DIR/web2py/applications/eden/models"
fi

if [ ! -f "$INSTALL_DIR/web2py/applications/eden/cron/crontab" ]; then
	cp "$INSTALL_DIR/web2py/applications/eden/deployment-templates/cron/crontab" "$INSTALL_DIR/web2py/applications/eden/cron/crontab"
fi

# Stream Edit 000_config.py
sed -i 's|EDITING_CONFIG_FILE = False|EDITING_CONFIG_FILE = True|' "$INSTALL_DIR/web2py/applications/eden/models/000_config.py"
sed -i 's|127.0.0.1:8000|127.0.0.1|' "$INSTALL_DIR/web2py/applications/eden/models/000_config.py"
sed -i 's|deployment_settings.gis.spatialdb = False|deployment_settings.gis.spatialdb = True|' "$INSTALL_DIR/web2py/applications/eden/models/000_config.py"

# Stream Edit 000_config.py for Postgres Database
sed -i 's|database.db_type = "sqlite"|database.db_type = "postgres"|' "$INSTALL_DIR/web2py/applications/eden/models/000_config.py"
sed -i 's|database.password = "password"|database.password = "sahana"|' "$INSTALL_DIR/web2py/applications/eden/models/000_config.py"

# Perform the initial database Migration/Prepopulation 
cd "$INSTALL_DIR/web2py"
touch NEWINSTALL
sudo -H -u web2py python web2py.py -S eden -M -R applications/eden/static/scripts/tools/noop.py

# Stream Edit 000_config.py to disable migration
sed -i 's|deployment_settings.base.migrate = True|deployment_settings.base.migrate = False|' "$INSTALL_DIR/web2py/applications/eden/models/000_config.py"
sed -i 's|deployment_settings.base.prepopulate = True|deployment_settings.base.prepopulate = False|' "$INSTALL_DIR/web2py/applications/eden/models/000_config.py"

# Prepare to Add Geometry Column (from http://eden.sahanafoundation.org/wiki/InstallationGuidelinesPostgreSQL#AddGeometrycolumntogis_location)
cat << EOF > "$TMP_DIR/geometry.sql"
UPDATE public.gis_location SET wkt = 'POINT (' || lon || ' ' || lat || ')' WHERE gis_feature_type = 1;
SELECT AddGeometryColumn( 'public', 'gis_location', 'the_geom', 4326, 'GEOMETRY', 2 );
UPDATE public.gis_location SET the_geom = ST_SetSRID(ST_GeomFromText(wkt), 4326);
EOF
# Add Geometry Column
if [ -e "$TMP_DIR/geometry.sql" ]; then
    su -c - postgres "psql -d sahana -f '$TMP_DIR'/geometry.sql"
fi

# AutoPopulate (from http://eden.sahanafoundation.org/wiki/InstallationGuidelinesPostgreSQL#AddGeometrycolumntogis_location)
cat << EOF > "$TMP_DIR/autopopulate.sql"
CREATE OR REPLACE FUNCTION s3_update_geometry()
  RETURNS "trigger" AS \$$
  DECLARE
  BEGIN
    if (NEW.wkt != '') then
        NEW.the_geom = SetSRID(GeomFromText(NEW.wkt), 4326);
        end if;

    RETURN NEW;
  END;
\$$  LANGUAGE 'plpgsql' VOLATILE;
ALTER FUNCTION s3_update_geometry() OWNER TO sahana;
CREATE TRIGGER s3_locations_update
  BEFORE INSERT
  ON gis_location
  FOR EACH ROW
  EXECUTE PROCEDURE s3_update_geometry();

EOF
# Import Autopopulate
if [ -e "$TMP_DIR/autopopulate.sql" ]; then
    su -c - postgres "psql -d sahana -f '$TMP_DIR'/autopopulate.sql"
fi


# Apache configuration
# Enable Modules
a2enmod ssl
a2enmod rewrite
a2enmod wsgi

#Create Sahana Conf for Apache2
cat << EOF > "$SAHANA_CONF"
<VirtualHost *:80>
ServerName eden
DocumentRoot /usr/share/web2py/applications  

#Alias /eden/static "$INSTALL_DIR/web2py/applications/eden/static"
WSGIScriptAlias / $INSTALL_DIR/web2py/wsgihandler.py
WSGIDaemonProcess web2py user=web2py group=web2py home=$INSTALL_DIR/web2py processes=2 maximum-requests=20
###Uncomment to Login VIa SSL/HTTPS#####
#RewriteEngine On
#RewriteRule ^/eden/default/user/(.*)$ https://%{http_HOST}/eden/default/user/$1 [R]

RewriteEngine On
RewriteCond %{REQUEST_URI} !/eden/(.*)
RewriteRule /(.*) /eden/$1 [R]

###Admin only accessible via SSH Tunnel###
<Location "/admin">
SSLRequireSSL
</Location>
###AppAdmin requires SSL####
#<LocationMatch "^(/[\w_]*/appadmin/.*)">
#SSLRequireSSL
#</LocationMatch>

### static files do not need WSGI
<LocationMatch "^(/[\w_]*/static/.*)">
    Order Allow,Deny
    Allow from all
  </LocationMatch>
  # everything else goes over WSGI
  <Location "/">
    Order deny,allow
    Allow from all
    WSGIProcessGroup web2py
  </Location>
ErrorLog /var/log/apache2/eden_error.log
LogLevel warn
CustomLog /var/log/apache2/eden_access.log combined
</VirtualHost>
EOF

#Clean TMP_DIR
rm -R "$TMP_DIR"
#enable sahana
a2ensite sahana
a2dissite 000-default
#stop services
service apache2 stop
service postgresql-8.4 stop
