#!/bin/bash -e

usage() {
cat <<EOF
$0 [-h | -d | -b] [-n NAME | -e DB Name] [-u MySQL user] [-t MySQL host] FQDN

Creates by default a Wordpress mysql configuration depending on required fully
qualified domain name(FQDN).

Options:
    -n name for the wordpress site; see also -e below
    -h help
    -d destroy and purge
    -b backup
    -u mysql username, will require password
    -t mysql server hostname, if unset localhost will be used
    -e existing empty mysql database name; will replace -n

Example: You want your blog to be served from http://blog.example.com
         for user 'wordpress'.

Then run:
sudo bash setup-mysql -n wordpress blog.example.com

EOF
}

checkforexistingsetup() {
if [ -f $CONFIG_FILE ] ; then
    echo WARNING: $CONFIG_FILE exists!
    exit 1
fi

# Generate a random password without Perl
MATRIX="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
if [ ! $MYSQLUSER ]; then
    LENGTH="8"
    while [ "${n:=1}" -le "$LENGTH" ]
    do
        DB_PASSWORD="$DB_PASSWORD${MATRIX:$(($RANDOM%${#MATRIX})):1}"
        let n+=1
    done
    DB_USER=$NAME
else
    DB_USER=$MYSQLUSER
    echo "Enter MySQL password for user $DB_USER."
    read -p "> " DB_PASSWORD
fi

LENGTH="50"
while [ "${n:=1}" -le "$LENGTH" ]
do
    SECRET_KEY="$SECRET_KEY${MATRIX:$(($RANDOM%${#MATRIX})):1}"
    let n+=1
done

if [ ! $DB_DB ]; then
    DB_NAME=$NAME
else
    DB_NAME=$DB_DB
fi

# Write the config file for wordpress
(umask 0027;
cat > $CONFIG_FILE << EOF
<?php
# Created by $0 $@
define('DB_NAME', '$DB_NAME');
define('DB_USER', '$DB_USER');
define('DB_PASSWORD', '$DB_PASSWORD');
define('DB_HOST', '$DB_HOST');
define('SECRET_KEY', '$SECRET_KEY');
define('WP_CONTENT_DIR', '$CONTENT');
?>
EOF
)
chgrp www-data "${CONFIG_FILE}"
echo $CONFIG_FILE written
}

create() {
# Create the database and user
# Wordpress's install.php creates the tables btw
if [ ! $DB_DB ]; then
    MYSQLCOMMAND="mysql -u $DB_USER -p -h $DB_HOST"
    $MYSQLCOMMAND <<EOF
CREATE DATABASE $NAME;
CREATE USER $DB_USER@$DB_HOST
IDENTIFIED WITH mysql_native_password BY '$DB_PASSWORD';
GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,ALTER
ON $DB_NAME.*
TO $DB_USER@$DB_HOST;
FLUSH PRIVILEGES;
EOF
fi

echo Goto http://$DOMAIN to setup Wordpress
}

backup() {
echo Enter root password for mysql:
BACKUPFILE=/tmp/blog-$NAME.bak.sql.bz2
mysqldump --add-drop-table -u root -p $NAME | bzip2 -c > $BACKUPFILE && echo Wrote $BACKUPFILE
}

destroy() {
# The destroy method need root to be able to drop databases and such.
# People using complex setups with remote servers probably know how to
# cleanup after the user any way.
if [ ! -e /etc/mysql/debian.cnf ]; then
    echo "Default mysql settings not available. Manual clean up is required."
    exit 1
fi
echo Destroying $NAME
prompt
mysql /etc/mysql/debian.cnf <<EOF
CONNECT mysql;
delete from user where user='$NAME';
DELETE FROM db WHERE User = '$NAME';
DELETE FROM tables_priv WHERE User = '$NAME';
DELETE FROM columns_priv WHERE User = '$NAME';
FLUSH PRIVILEGES ;
DROP DATABASE IF EXISTS $NAME;
EOF
rm $CONFIG_FILE
}

prompt() {
while true; do
  echo -n "Are you sure? (y/n) "
  read yn
  case $yn in
    y* | Y* ) break ;;
    [nN]* )   exit 0 ; break ;;
    * ) echo "unknown response.  Asking again" ;;
  esac
done
}


while getopts "n:hbdu:t:e:-" opt ; do
    case "$opt" in
    h) usage ; exit 0 ;;
    b) BACKUP=1 ;;
    d) DESTROY=1 ;;
    n) NAME="$OPTARG" ;;
    u) MYSQLUSER="$OPTARG" ;;
    t) DB_HOST="$OPTARG" ;;
    e) DB_DB="$OPTARG" ;;
    -) break ;;
    *) usage 1>&2 ; exit 1 ;;
    esac
done
shift $(($OPTIND - 1))

if [ "$(id -u)" != "0" ]
then
  echo "You must be root to use this script."
  exit 1
fi

DOMAIN=$(echo $1 | tr "[:upper:]" "[:lower:]")
CONTENT="/var/lib/wordpress/wp-content"

if [ $DOMAIN ] ; then
ping -c 1 `echo $DOMAIN | sed 's/:[0-9]\+//'` || exit 1
else
    usage
    exit 0
fi

CONFIG_FILE=/etc/wordpress/config-$DOMAIN.php

if [ ! $NAME ] ; then
NAME=$(echo $DOMAIN | sed 's,\.,,g;s,-,,g')
echo Constructed database name and user: $NAME from $DOMAIN
fi

if [ ${#NAME} -gt 16 ]; then
echo "$NAME is longer than MySQL's limit of 16 characters. Please specify a shorter one."
exit 1
fi

if [ ! $DB_HOST ]; then
    DB_HOST="localhost"
fi

if [ $BACKUP ] ; then
backup
exit 0
fi

if [ $DESTROY ] ; then
destroy
exit 0
fi

checkforexistingsetup
create
