#!/bin/bash
#
# fixperms - Fixes the permissions of your newly minted Apache instance
# 
# 

# Symlinks we need to create to get Apache2 running
SYMLINKS="./etc/apache2/logs:../../var/log/apache2
./etc/apache2/mods-enabled:/etc/apache2/mods-enabled
./etc/apache2/mods-available:/etc/apache2/mods-available
./etc/apache2/modules:/usr/lib/apache2/modules
./etc/apache2/mime/mime.types:/etc/mime.types
./etc/apache2/mime/magic:/etc/magic
./etc/apache2/include/php5.conf:php5-debug.conf
./etc/ssl:/etc/ssl
./etc/apache2/sites-enabled/mass-vhost.conf:../sites-available/mass-vhost.conf"

# Directories that need to be owned and writable by Apache
APACHEDIRS="./var/log
./var/log/xdebug
./var/log/apache2
./var/spool/mail"

# Stuff you should own but Apache needs to read
YOURSTUFF="./www
./www/localhost
./www/localhost/*"

# Determine the name of this service
service_name() {
    DIR=`dirname $0`
    pushd "${DIR}" > /dev/null
    TOP=`pwd | cut -d / -f 2`
    SERVICE=`pwd | cut -d / -f 3`
    popd > /dev/null
   
    # verify this is under the /srv mountpoint 
    if [ "${TOP-error}" = "srv" ]
    then
        echo $SERVICE
    else
        return 1;
    fi
}

# Make sure we are not root
if [ $UID -eq 0 ]; then
    echo "You must run $0 as your development user, not root!"
    exit
fi

# Make sure files are in a subdir of /srv
SERVICE_NAME=`service_name`
ONSRV=$?
if [ $ONSRV -eq 1 ]; then
   echo "Not located in /srv/"
   exit
fi

# push directory on the stack
pushd /srv/$SERVICE_NAME || exit

# make symlinks where needed
echo "Creating required symlinks:"
for LINKLINE in $SYMLINKS; do
    LINK=`echo $LINKLINE | cut -d: -f1`
    TARGET=`echo $LINKLINE | cut -d: -f2`

    # check for an existing file with that name
    if [ -e $LINK ]; then
        echo "    $LINK exists"
    else
        sudo ln -s $TARGET $LINK && echo "    $LINK -> $TARGET" || echo "    $LINK failed to link $TARGET"
    fi
        
done

# give apache ownership of its directories
echo "Giving Apache2 ownership of:"
for DIR in $APACHEDIRS; do
    echo '   ' $DIR
    sudo chown -R www-data $DIR
    sudo chmod -R u+w,g-w,o-w,a+rX $DIR
done

# give you owndership of your directories
echo "Giving $USER ownership of: "
for DIR in $YOURSTUFF; do
    echo '   ' $DIR
    sudo chown $USER $DIR
    sudo chmod u+ws,g-w,o-w,a+rX $DIR
done

