#!/bin/bash

### predefined constants ###

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_DEFAULT="define('WPLANG', '');"
WP_CONFIG_LANG="define('WPLANG', 'cs_CZ');";
WP_CONFIG_CUSTOM="define('FS_METHOD', 'direct');"
WP_CONFIG_CUSTOM_BEFORE="/* That's all, stop editing! Happy blogging. */"

### helper functions ###

COLOUR_BTW='\033[90m'
COLOUR_WHITE='\033[01;37m'
COLOUR_RESTORE='\033[0m'
COLOUR_RED='\033[91m'

function echo_white() {
    echo -e "$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:]'
}

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

# web domain
read -p "Enter host name (e.g. for http://blog.zaantar.eu enter blog.zaantar.eu) and press [ENTER]: " WP_HOSTNAME
WP_HOSTNAME=$(strip_trailing_slashes $WP_HOSTNAME)
echo_btw "WP_HOSTNAME=$WP_HOSTNAME"
echo

# wordpress installation
read -p "Enter WordPress installation location relative to $WWW_BASEDIR and press [ENTER]: " 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 "Enter ownership information for WordPress files (default is $DEFAULT_USER:$DEFAULT_GROUP) and press [ENTER]: " 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 (default)?"
read -p "Your choice [ENTER]: " CHMOD_OPTION
CHMOD_OPTION=$(lowercase $CHMOD_OPTION)
#if [ "$CHMOD_OPTION" == "a" ];
#then
#	CHMOD_PATH="$WWW_BASEDIR"
#else
if [ "$CHMOD_OPTION" == "a" ];
then
	CHMOD_PATH="$WWW_BASEDIR$WP_FIRST_DIR"
else
	CHMOD_PATH="$WP_PATH"
fi
#fi
echo_btw "CHMOD_PATH = $CHMOD_PATH"
echo

# lighttpd
read -p "Enter lighttpd config file to append to (default is $DEFAULT_LIGHTTPD_CONFIG_FILE) and press [ENTER]: " 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)? [ENTER]: " MYSQL_CREATE
MYSQL_CREATE=$(lowercase $MYSQL_CREATE)
echo

if [ "$MYSQL_CREATE" != "n" ];
then
    # mysql database name
    read -p "Enter mySQL database and user name for new WordPress installation and press [ENTER]: " MYSQL_DB_NAME
    MYSQL_USER_NAME=$MYSQL_DB_NAME
    echo

    # mysql root password
    read -s -p "Enter mySQL root password and press [ENTER]: " MYSQL_ROOT_PASSWORD
    echo
fi

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"

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

### manual wordpress setup  ###
echo_white "Stage 4: Manual setup"

echo "Now you should manually finish your WordPress setup."

if [ "$MYSQL_CREATE" != "n" ];
then
    echo "DB name: $COLOUR_RED$MYSQL_DB_NAME$COLOUR_RESTORE"
    echo "DB user: $COLOUR_RED$MYSQL_USER_NAME$COLOUR_RESTORE"
    echo "DB pasword: $COLOUR_RED$MYSQL_USER_PASSWORD$COLOUR_RESTORE"
fi

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

read -p "Press any key after you finished the setup... " -n1 -s
echo


### adjust wp-config.php ###
echo_white "Stage 5: wp-config.php"

echo "Configuring WordPress language..."
replace "$WP_CONFIG_LANG_DEFAULT" "$WP_CONFIG_LANG" -- "$WP_PATH/wp-config.php"

echo "Adding custom configuration..."
replace "$WP_CONFIG_CUSTOM_BEFORE" "$WP_CONFIG_CUSTOM"$'\n'"$WP_CONFIG_CUSTOM_BEFORE" -- "$WP_PATH/wp-config.php"

### wp-cli ###
echo_white "Stage 6: Initial site configuration"
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!"
