#!/bin/bash
#set -vx 

# path to your markus development instance ("world" 
# has at least read permission of this directory and files in there
MARKUS_RAILS_ROOT=/path/to/rails/app

# Shouldn't need to change this
LOGFILE="$(pwd)/apache_proxy_auth_setup.log"
APACHE_CONFIG_FILE="/etc/apache2/sites-available/01_markus_auth_setup.conf"
APACHE_PROXY_CONF_FILE="/etc/apache2/mods-available/proxy.conf"
MARKUS_HOST="testhost.com"
APACHE_PW_FILE="/etc/apache2/markus_auth_users.db"
AUTH_USER="markus_test"
AUTH_PASSWD="test"

# should be root
if [ $(id -u) -ne 0 ]; then
  echo 1>&2 "This script needs to be run as root!"
  exit 1
fi

# remove old logfiles
if [ -e $LOGFILE ]; then
  rm $LOGFILE
fi

echo -e "\nChecking if required software is installed ..."
for package in apache2-mpm-prefork apache2-utils; do
  echo -en "\t$package "
  if dpkg-query -W -f='${Package}' $package > /dev/null 2>&1; then
    echo " is installed"
  else
    echo -n " is NOT installed. Installing ..."
    # do the install
    aptitude update >> $LOGFILE 2>&1
    aptitude -y install $package >> $LOGFILE 2>&1
    if [ $? -eq 0 ]; then
      echo " successful."
    else
      echo " failed."
    fi
  fi
done
echo -e "Required software check done.\n"

echo -en "Setting up apache configuration ..."
if ! [ -e /var/www/$MARKUS_HOST ]; then
  # create dummy docroot
  mkdir -p /var/www/$MARKUS_HOST
fi
# virtual host
cat > $APACHE_CONFIG_FILE <<EOF
<VirtualHost *:80>
	ServerAdmin $AUTH_USER@localhost.localdomain
	ServerName $MARKUS_HOST
	ServerSignature off
	
	DocumentRoot /var/www/$MARKUS_HOST
	<Directory />
		Options FollowSymLinks
		AllowOverride None
	</Directory>
	<Directory /var/www/$MARKUS_HOST>
		Options FollowSymLinks MultiViews
		AllowOverride None
		Order allow,deny
		allow from all
	</Directory>

	ErrorLog /var/log/apache2/$MARKUS_HOST.error.log

	# Possible values include: debug, info, notice, warn, error, crit,
	# alert, emerg.
	LogLevel info

	CustomLog /var/log/apache2/$MARKUS_HOST.access.log combined

	RewriteEngine On
	# define proxy balancer
	<Proxy balancer://mongrel>
     		BalancerMember http://127.0.0.1:3000 retry=100
 	</Proxy>

	# Auth config (REMOTE_USER testing)
	<Location /markus>
		# Make sure we do some markus foreign authentication
		Authname "Authenticate yourself!"
		AuthType basic
		AuthUserFile $APACHE_PW_FILE
		Require valid-user
	</Location>
 	Alias /markus $MARKUS_RAILS_ROOT/public
 	<Directory $MARKUS_RAILS_ROOT/public>
     		Options Indexes FollowSymLinks MultiViews
     		AllowOverride None
     		Order allow,deny
     		allow from all
 	</Directory>
	# read REMOTE_USER variable and set HTTP header so that it gets
	# passed on to mongrel
	RewriteCond %{LA-U:REMOTE_USER} (.+)
	RewriteRule . - [E=RU:%1]
	RequestHeader add X-Forwarded-User %{RU}e

	RewriteCond %{REQUEST_FILENAME} !/markus/(images|stylesheets|javascripts)
 	RewriteRule ^/markus.*$ balancer://mongrel%{REQUEST_URI} [P,QSA,L]
</VirtualHost>
EOF

# enable site/modules
for module in proxy proxy_balancer proxy_http headers rewrite; do
  a2enmod $module >> $LOGFILE 2>&1
done
a2ensite $(basename $APACHE_CONFIG_FILE) >> $LOGFILE 2>&1

# write proxy.conf
if [ -e $APACHE_PROXY_CONF_FILE ]; then
  mv $APACHE_PROXY_CONF_FILE ${APACHE_PROXY_CONF_FILE}.old
fi
cat > $APACHE_PROXY_CONF_FILE <<EOF
<IfModule mod_proxy.c>
        #turning ProxyRequests on and allowing proxying from all may allow
        #spammers to use your proxy to send email.

        ProxyRequests Off

        <Proxy http://$MARKUS_HOST/*>
                AddDefaultCharset off
                Order deny,allow
                Deny from all
                Allow from 127.0.0.1
        </Proxy>

        # Enable/disable the handling of HTTP/1.1 "Via:" headers.
        # ("Full" adds the server version; "Block" removes all outgoing Via: headers)
        # Set to one of: Off | On | Full | Block

        ProxyVia On
</IfModule>
EOF

# write user authentication file
if [ -e $APACHE_PW_FILE ]; then
  # exists, update only
  htpasswd -b $APACHE_PW_FILE $AUTH_USER $AUTH_PASSWD >> $LOGFILE 2>&1
else
  htpasswd -cb $APACHE_PW_FILE $AUTH_USER $AUTH_PASSWD >> $LOGFILE 2>&1
fi

echo "Checking apache configuration syntax" >> $LOGFILE
apache2ctl configtest >> $LOGFILE 2>&1
echo "Done." >> $LOGFILE

echo " Done." # end Apache stuff

echo -en "\nUpdating /etc/hosts file ..."
if ! grep -q $MARKUS_HOST /etc/hosts; then
  # add to vhost as localhost alias
  sed -i "s/^\(127.0.0.1.*\)\$/\1 $MARKUS_HOST/" /etc/hosts
fi
echo -e " Done.\n"

# Start apache
if /etc/init.d/apache2 status | grep -q 'pid'; then
  # restart
  /etc/init.d/apache2 restart
else
  /etc/init.d/apache2 start
fi

echo -e "\nAll done!\n"
exit 0 # horray!

