#!/usr/bin/bash
#
# Installs drupal in destination directory. You may
# need to change DP_FILE to what version you need.
# Requirements: Must have HTTP virtual host already setup.
# Copyright (c) 2016 Joyent Inc., All rights reserved.

usage() {
cat << EOF

Usage: $0 [options] DIRECTORY

Arguments:
    
    DIRECTORY        Directory to install drupal.

Options:
    
    -u               Username to access database.  [use portal credentials]
    -p               Password to access database.  [use portal credentials]

EOF
exit 2;
}

while getopts "u:p:" OPTION; do
        case $OPTION in
                u)
                        DB_USER=$OPTARG;
                        ;;
                p)
                        DB_PASS=$OPTARG;
                        ;;
                *)
                        usage;
                        ;;
        esac
done

shift $(($OPTIND - 1))
if [[ $# = 1 ]]; then
        DP_DIR=$1;
else
        usage;
fi

export LANG=C
PATH="/opt/local/bin:/opt/local/gnu/bin:/opt/local/sbin:/usr/bin:/usr/sbin";
DB_USER=${DB_USER:-root};
DB_PASS=${DB_PASS:-`mdata-get mysql_pw 2>/dev/null`};
DP_USER=dp_$(zonename | awk -F\- '{ print $5 }');
DP_PASS=$(od -An -N8 -x /dev/random | head -1 | sed 's/^[ \t]*//' | tr -d ' ');
DP_DB=dp_$(od -An -N3 -x /dev/random | head -1 | sed 's/^[ \t]*//' | tr -d ' ');
DP_FILE="drupal-7.16.tar.gz";
DP_URL="http://ftp.drupal.org/files/projects/${DP_FILE}";

# Check for tools in PATH
for i in wget gtar gsed sm-create-db sm-create-dbuser mysql; do
        hash $i &>/dev/null
        [[ $? -eq 1 ]] && echo "* ERROR - $i was not found in your PATH." && exit 2;
done

# Check if MySQL is running
[[ ! `pgrep mysqld` ]] && echo "* ERROR - mysql must be running to create the database for wordpress." && exit 2;

# Check that we can connect with DB_USER DB_PASS
mysql -u${DB_USER} -p${DB_PASS} -e "select version();" > /dev/null 2>&1
[[ $? -eq 1 ]] && echo "* ERROR - Can't connect to mysql with username password specified." && exit 2;

# Check if destination directory exists
[[ ! -d ${DP_DIR} ]] && mkdir ${DP_DIR};

# Download and extract drupal
echo "* Downloading drupal.";

wget ${DP_URL} -O ${DP_DIR}/${DP_FILE} > /dev/null 2>&1
[[ $? > 0 ]] && echo "* ERROR - There was an error getting ${DP_URL}." && exit 2;

gtar zxvf ${DP_DIR}/${DP_FILE} -C ${DP_DIR} --strip=1 > /dev/null 2>&1
[[ $? > 0 ]] && echo "* ERROR - There was an error extracting ${DP_FILE} to ${DP_DIR}." && exit 2;

# Configure drupal
echo "* Configuring drupal.";

cp ${DP_DIR}/sites/default/default.settings.php ${DP_DIR}/sites/default/settings.php
chown -R www:www ${DP_DIR}
chmod 666 ${DP_DIR}/sites/default/settings.php

# Create drupal database and user pass
sm-create-db -u${DB_USER} -p${DB_PASS} mysql ${DP_DB}

sm-create-dbuser -u${DB_USER} -p${DB_PASS} mysql ${DP_USER} ${DP_PASS} ${DP_DB}

echo "* Visit http://x.x.x.x/install.php to finish the install.";
