#!/bin/bash

#################################################################################
#	wpdeploy.sh																	#
#################################################################################
#																				#
#	A bash script for easy deployment of WordPress site on Gentoo with 			#
#	lighttpd web server.														#
#																				#
#	See http://bit.ly/1cAuCAC for more information.								#
#																				#
#	Copyright (C) 2013 Zaantar (zaantar@zaantar.eu)								#
#																				#
#################################################################################
#																				#
#	This program is free software: you can redistribute it and/or modify		#
#	it under the terms of the GNU General Public License as published by		#
#	the Free Software Foundation, either version 3 of the License, or			#
#	(at your option) any later version.											#
#																				#
#	This program 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 General Public License for more details.								#
#																				#
#	You should have received a copy of the GNU General Public License			#
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.		#
#																				#
#################################################################################

### predefined constants ###

# names of these variables are quite self-explanatory...
WWW_BASEDIR=/var/www/
DOWNLOAD_URL=http://wordpress.org/latest.tar.gz
DEFAULT_GROUP=lighttpd
DEFAULT_USER=lighttpd
LIGHTTPD_CONFIG_PATH=/etc/lighttpd/
DEFAULT_LIGHTTPD_CONFIG_FILE=lighttpd.conf
WP_CONFIG_LANG="cs_CZ";
WP_CONFIG_CUSTOM="define('FS_METHOD', 'direct');"
DEFAULT_ADMIN_USER="zaantar"
DEFAULT_ADMIN_EMAIL="zaantar@zaantar.eu"

### helper functions ###

# values for terminal output formatting
COLOUR_BTW='\033[90m'
COLOUR_WHITE='\033[01;37m'
COLOUR_RESTORE='\033[0m'
COLOUR_RED='\033[91m'

function echo_white() {
    echo -e "\n$COLOUR_WHITE$1$COLOUR_RESTORE"
}

function echo_btw() {
    echo -e "$COLOUR_BTW$1$COLOUR_RESTORE"
}

function strip_trailing_slashes() {
	echo `sed 's#/*$##;s#^/*##' <<< $1`
}

function lowercase() {
	echo $1 | tr '[:upper:]' '[:lower:]'
}

### introduction ###
echo_white "wpdeploy.sh"
echo "Copyright (C) 2013 Zaantar (zaantar@zaantar.eu)"
echo "This program comes with ABSOLUTELY NO WARRANTY."
echo "This is free software, and you are welcome to redistribute it"
echo "under certain conditions. See http://www.gnu.org/licenses/ for details."
echo

### user input ###
echo_white "Stage 0: Data collection."

# web domain
read -p "Host name (e.g. for http://blog.zaantar.eu enter blog.zaantar.eu): " WP_HOSTNAME
WP_HOSTNAME=$(strip_trailing_slashes $WP_HOSTNAME)
WP_URL="http://$WP_HOSTNAME"
echo_btw "WP_HOSTNAME=$WP_HOSTNAME"
echo

# wordpress installation
read -p "WordPress installation location relative to $WWW_BASEDIR: " WP_RELATIVEDIR
WP_RELATIVEDIR=$(strip_trailing_slashes $WP_RELATIVEDIR)
WP_PATH="$WWW_BASEDIR$WP_RELATIVEDIR"
echo_btw "WP_PATH=$WP_PATH"
echo

# file group and owner
read -p "Owner (or owner:group) for WordPress files [$DEFAULT_USER:$DEFAULT_GROUP]: " OWNERS
if [ -z "$OWNERS" ];
then
    OWNERS="$DEFAULT_USER:$DEFAULT_GROUP"
fi
echo_btw "OWNERS=$OWNERS"
echo

# what to chmod?
WP_FIRST_DIR=`echo $WP_RELATIVEDIR | cut -f1 -d"/"`
echo_btw "WP_RELATIVEDIR = $WP_RELATIVEDIR, WP_FIRST_DIR = $WP_FIRST_DIR"
echo -e "Do you want to chmod and chown from \n\t(a) $WWW_BASEDIR$WP_FIRST_DIR\nor\t(b) $WP_PATH?"
read -p "Your choice [b]: " CHMOD_OPTION
CHMOD_OPTION=$(lowercase $CHMOD_OPTION)
if [ "$CHMOD_OPTION" == "a" ];
then
	CHMOD_PATH="$WWW_BASEDIR$WP_FIRST_DIR"
else
	CHMOD_PATH="$WP_PATH"
fi
echo_btw "CHMOD_PATH = $CHMOD_PATH"
echo

# lighttpd
read -p "lighttpd config file to append to [$DEFAULT_LIGHTTPD_CONFIG_FILE]: " LIGHTTPD_CONFIG_FILE
if [ -z "$LIGHTTPD_CONFIG_FILE" ];
then
    LIGHTTPD_CONFIG_FILE=$DEFAULT_LIGHTTPD_CONFIG_FILE
fi
LIGHTTPD_CONFIG_FILE="$LIGHTTPD_CONFIG_PATH$LIGHTTPD_CONFIG_FILE"
echo_btw "LIGHTTPD_CONFIG_FILE=$LIGHTTPD_CONFIG_FILE"
echo

# manipulate with database?
read -p "Create new database (Y/n)?: " MYSQL_CREATE
MYSQL_CREATE=$(lowercase $MYSQL_CREATE)
echo

# mysql database name
read -p "MySQL database and user name for WordPress: " MYSQL_DB_NAME
MYSQL_USER_NAME=$MYSQL_DB_NAME
echo

if [ "$MYSQL_CREATE" != "n" ];
then
    # mysql root password
    read -s -p "MySQL root password: " MYSQL_ROOT_PASSWORD
    echo
else
    # mysql user password
    read -s -p "Password for the database: " MYSQL_USER_PASSWORD
    echo
fi

# wp credentials
read -p "Site title [$WP_HOSTNAME]: " SITE_TITLE
if [ -z "$SITE_TITLE" ];
then
    SITE_TITLE=$WP_HOSTNAME
fi
echo


read -p "WordPress admin username [$DEFAULT_ADMIN_USER]: " ADMIN_USER
if [ -z "$ADMIN_USER" ];
then
    ADMIN_USER=$DEFAULT_ADMIN_USER
fi
echo_btw "ADMIN_USER=$ADMIN_USER"
echo


read -p "WordPress admin e-mail [$DEFAULT_ADMIN_EMAIL]: " ADMIN_EMAIL
if [ -z "$ADMIN_EMAIL" ];
then
    ADMIN_EMAIL=$DEFAULT_ADMIN_EMAIL
fi
echo_btw "ADMIN_EMAIL=$ADMIN_EMAIL"
echo

read -p "Press any key to begin... " -n1 -s
echo

### copy wordpress files ###
echo_white "Stage 1: Download and extract WordPress files."

echo "Create target directory $WP_PATH..."
mkdir --parents $WP_PATH

echo "Download wordpress files and extract them..."
wget -O - $DOWNLOAD_URL | tar -zxf - --directory $WP_PATH --strip 1


### configure lighttpd ###
echo_white "Stage 2: Lighttpd"

# see http://zaantar.eu/2013/06/domaci-server-s-gentoo-wordpress-na-lighttpd/ (czech)
# for more information about wordpress on lighttpd
echo "Configuring lighttpd file..."
echo "$(cat <<EOF

# WordPress configuration for $WP_RELATIVEDIR
# Generated by wpdeploy.sh (http://zaantar.eu)
\$HTTP["host"] =~ "(^|www\.)$WP_HOSTNAME" {
    server.document-root = var.basedir + "/$WP_RELATIVEDIR"
    url.rewrite-final = (
        "^/(wp-admin|wp-includes|wp-content)/(.*)" => "\$0", # Exclude some directories from rewriting
        "^/(.*.php)" => "\$0", # Exclude .php files at root from rewriting
        "^/(.*)$" => "/index.php/\$1" # Handle permalinks and feeds
    )
}

EOF
)" >> $LIGHTTPD_CONFIG_FILE


echo "Restarting lighttpd service..."
rc-service lighttpd restart


### create mysql database ###
echo_white "Stage 3: MySQL database."

if [ "$MYSQL_CREATE" != "n" ];
then

    echo "Generate password for new user..."
    MYSQL_USER_PASSWORD=$( < /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-32})

    echo "Create the database..."
    echo "create database $MYSQL_DB_NAME; grant all on $MYSQL_DB_NAME.* to '$MYSQL_USER_NAME'@'localhost' identified by '$MYSQL_USER_PASSWORD';" |  mysql -v -u root --password=$MYSQL_ROOT_PASSWORD

else
    echo "Skipping..."
fi


### wordpress config ###
echo_white "Stage 4: wp-config.php"

echo "CD to $WP_PATH..."
cd "$WP_PATH"

# now we start using WP CLI. you should see http://wp-cli.org/ for more information
echo "Create wp-config.php file..."
wp core config --dbname=$MYSQL_DB_NAME --dbuser=$MYSQL_USER_NAME --dbpass=$MYSQL_USER_PASSWORD --locale=$WP_CONFIG_LANG --extra-php <<PHP

$WP_CONFIG_CUSTOM

PHP


### installation ###
echo_white "Stage 5: Installation"

# generate password for admin
ADMIN_PASSWORD=$( < /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-32})
echo -e "WordPress admin password: $COLOUR_RED$ADMIN_PASSWORD$COLOUR_RESTORE"

wp core install --url="$WP_URL" --title="$SITE_TITLE" --admin_user="$ADMIN_USER" --admin_email="$ADMIN_EMAIL" --admin_password="$ADMIN_PASSWORD"

### initial configuration ###
echo_white "Stage 6: Initial site configuration"

# install "default" plugins and themes (for my purposes)
wp plugin install wordpress-logging-service --activate
wp plugin install superadmin-helper --activate
wp plugin install login-security-solution --activate
wp plugin install reply-to
wp plugin install codestyling-localization --activate
wp plugin install hotfix --activate
wp plugin install wp-maintenance-mode --activate
wp plugin install admin-bar-login
wp plugin install backwpup
wp plugin install http://genesisthemes.de/wp-content/uploads/2013/05/backwpup-humility_100-rc1.zip --activate
wp plugin install automatic-updater
wp plugin install wordpress-language --activate
wp theme install montezuma


### cleanup ###
echo_white "Stage 7: Polishing and cleanup"

echo "Change user ownership and permissions..."
echo_btw "CHMOD_PATH = $CHMOD_PATH, OWNERS = $OWNERS"
chown -R "$OWNERS" "$CHMOD_PATH"
chmod -R ug+rwx "$CHMOD_PATH"


### finished ###
echo_white "Finished. Happy blogging!"
