#!/bin/bash -x
################## update base packages ##################
apt-get update
apt-get install sudo htop apache2 php5 php5-fpm php5-cli git
################## join active directory ##################
wget http://download.beyondtrust.com/PBISO/8.3/pbis-open-8.3.0.3287.linux.x86_64.deb.sh
chmod a+x pbis-open-8.3.0.3287.linux.x86_64.deb.sh
./pbis-open-8.3.0.3287.linux.x86_64.deb.sh
echo "%domain^admins ALL=(ALL) ALL" > /etc/sudoers.d/activedirectory
/opt/pbis/bin/domainjoin-cli join scimonshouse.net stwalkerster
############## install FPM / Apache2 #######################
cat /etc/php5/fpm/pool.d/www.conf | \
   sed 's/\[www\]/[phabricator]/' | \
   sed 's/^user = www-data/user = phabricator/' | \
   sed 's/^group = www-data/group = phabricator/' | \
   sed 's#^listen = /var/run/php5-fpm.sock#listen = localhost:30000#' \
   > /etc/php5/fpm/pool.d/phabricator.conf
a2enmod access_compat alias cgi dir env expires filter headers proxy proxy_fcgi proxy_http rewrite
cat /etc/apache2/sites-enabled/000-default | \
   sed '/<\/VirtualHost>/ i\' | \
   sed '/<\/VirtualHost>/ i\        SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1' | \
   sed '/<\/VirtualHost>/ i\' | \
   sed '/<\/VirtualHost>/ i\        RewriteEngine on' | \
   sed '/<\/VirtualHost>/ i\        RewriteRule ^/rsrc/(.*)     -                       [L,QSA]' | \
   sed '/<\/VirtualHost>/ i\        RewriteRule ^/favicon.ico   -                       [L,QSA]' | \
   sed '/<\/VirtualHost>/ i\        RewriteRule ^(.*)$          fcgi://127.0.0.1:30000/opt/phabricator/phabricator/webroot/index.php?__path__=$1  [B,L,QSA,P]' \
   > /etc/apache2/sites-enabled/000-default.new
mv /etc/apache2/sites-enabled/000-default /etc/apache2/sites-enabled/000-default.old
mv /etc/apache2/sites-enabled/000-default.new /etc/apache2/sites-enabled/000-default
service php5-fpm restart
service apache2 restart
##############  install phabricator #####################
mkdir /opt/phabricator
groupadd phabricator
useradd -d /opt/phabricator -M -s /bin/bash -g phabricator phabricator
cd /opt/phabricator
sudo -u phabricator git clone https://github.com/phacility/libphutil.git
sudo -u phabricator git clone https://github.com/phacility/arcanist.git
sudo -u phabricator git clone https://github.com/phacility/phabricator.git