#!/bin/sh -e

# This script handles the creation of a b2evolution database user and table.
# It is normally automatically run by debconf.
# Most of it is taken from the wordpress "setup-mysql" script.

usage() {
cat <<EOF
$0 [-h | -d | -b] [-e] [-u] FQDN BASE_URL DB_NAME

Creates by default a b2evolution mysql configuration depending on required fully
qualified domain name(FQDN), for a blog accessible at BASE_URL. 

Options:
    -h  help
    -d  destroy and purge
    -b  backup
    -e  create only the skeleton of the file,i.e. without database name & login
    -u  do not create database (used in case of package upgrade)

Example: You want your blog to be served from http://www.example.com/b2evolution
with a database named b2evolution then run:
sudo sh setup-config www.example.com http:///www.example.com/b2evolution b2evolution

EOF
}

gen_config() {
if [ -f $CONFIG_FILE ] ; then
	mv -f $CONFIG_FILE $CONFIG_FILE.back
fi

if [ -z "$OLD_DB_PASSWORD" ] ; then

     # Generate a random password
     [ -x /usr/bin/makepasswd ] && \
     DB_PASSWORD=`makepasswd --chars 12 --randomseed 0`
else
     DB_PASSWORD=$OLD_DB_PASSWORD
fi

if [ ! -z "$OLD_DB_USER" ] ; then
   DB_USER=$OLD_DB_USER
fi

if [ ! -z "$OLD_DB_NAME" ] ; then
   DB_NAME=$OLD_DB_NAME
fi

if [ ! -z "$OLD_BASE_URL" ]; then
    BASE_URL=$OLD_BASE_URL
fi

if [ ! -z "$OLD_ADMIN_EMAIL" ]; then
    ADMIN_EMAIL=$OLD_ADMIN_EMAIL
else
    ADMIN_EMAIL=postmaster@$DOMAIN
fi

# Write the config file for b2evolution
cat > $CONFIG_FILE << EOF
<?php
/**
 * This is b2evolution's basic config file.
 *
 * You need to edit this file to your settings before attempting to install the database!
 * Last significant changes to this file: version 1.6
 *
 *
 * Reminder: every line starting with # or // is a comment, multiline comments are
 *           surrounded by '/*' and '* /' (without space).
 *
 * IMPORTANT: Take special care not to erase quotes (') around text parameters
 * and semicolums (;) at the end of the lines. Otherwise you'll get some
 * "unexpected T_STRING" parse errors!
 *
 * Contributors: you should override this file by creating a file named _config_TEST.php
 * (see end of this file).
 *
 * @package conf
 */
if( !defined('EVO_CONFIG_LOADED') ) die( 'Please, do not access this page directly.' );


// TODO: dh> this file was meant to be used for things where you only need the basic config..
// fp> also:
// - At least _admin.php should only be called when in the backoffice.
// - Also we should probably start by moving as many conf options to the backoffice as possible and see how much stuff is left in conf files
//    Note: some stuff does not make sense in the back-office (for example stuff that depends on the physical path where the files are installed)
// - In view of reorganization, please list (all or examples) of situations where only a subset of the conf should be loaded.


/**
 * Maintenance mode. Set this to 1 in order to temporarily disable access to the application.
 *
 * Note: it is still possible to access the install script during maintenance mode.
 */
\$maintenance_mode = 0;


// Below is an alternative hardcore version of maintenance mode.
// This one will block the install script too.
// Remove /* and */ to activate.
/*
header('HTTP/1.0 503 Service Unavailable');
echo '<h1>503 Service Unavailable</h1>';
die( 'The site is temporarily down for maintenance.' );
*/


/**#@+
 * MySQL DB settings.
 * Fill in your database details (check carefully or nothing will work!)
 */
\$db_config = array(
    'user'          => '$DB_USER',        // your MySQL username
    'password'      => '$DB_PASSWORD', // ...and password
    'name'          => '$DB_NAME',     // the name of the database
    'host'          => 'localhost',    // MySQL Server (typically 'localhost')
);
/**#@-*/


/**
 * the tables prefix (gets placed before each b2evo table name),
 * use this to have multiple installations in one DB.
 *
 * @global string $tableprefix
 */
\$tableprefix = 'evo_';


/**
 * If you want to be able to reset your existing b2evolution tables and start anew
 * you must set $allow_evodb_reset to 1.
 *
 * NEVER LEAVE THIS SETTING ON ANYTHING ELSE THAN 0 (ZERO) ON A PRODUCTION SERVER.
 * IF THIS IS ON (1) AND YOU FORGET TO DELETE THE INSTALL FOLDER, ANYONE WOULD BE ABLE TO
 * ERASE YOUR B2EVOLUTION TABLES AND DATA BY A SINGLE CLICK!
 */
\$allow_evodb_reset = 0;	// Set to 1 to enable. Do not leave this on 1 on production servers


/**
 * $baseurl is where your blogs reside by default. CHECK THIS CAREFULLY or nothing will work.
 * It should be set to the URL where you can find the blog templates and/or the blog stub files,
 * that means index.php, blog_b.php, etc.
 * Note: Blogs can be in subdirectories of the baseurl. However, no blog should be outside
 * of there, or some tricky things may fail (e-g: pingback)
 *
 * IMPORTANT: If you want to test b2evolution on your local machine, do NOT use that machine's
 * name in the $baseurl!
 * For example, if your machine is called HOMER, do not use http://homer/b2evolution/blogs/ !
 * Use http://localhost/b2evolution/blogs/ instead. And log in on localhost too, not homer!
 * If you don't, login cookies will not hold.
 *
 * @global string $baseurl
 */
\$baseurl = '$BASE_URL';
// Use the following if you want to use the current domain:
/*
if( isset(\$_SERVER['HTTP_HOST']) )
{	// This only works if HOSt provided by webserver (i-e DOES NOT WORK IN PHP CLI MODE)
	\$baseurl = ( (isset(\$_SERVER['HTTPS']) && ( \$_SERVER['HTTPS'] != 'off' ) ) ?'https://':'http://')
							.\$_SERVER['HTTP_HOST'].'/';
}
*/

/**
 * This is used only to create the Admin account.
 * @todo move to installer.
 */
\$admin_email = '$ADMIN_EMAIL';


/**
 * Once you have edited this file to your settings, set the following to 1 (one):
 */
\$config_is_done = 1;


# IMPORTANT: you will find more parameters in the other files of the /conf folder.
# IT IS RECOMMENDED YOU DO NOT TOUCH THOSE SETTINGS
# UNTIL YOU ARE FAMILIAR WITH THE DEFAULT INSTALLATION.
#
# It is however strongly recommended you browse through these files as soon as you've
# got your basic installation working. They'll let you customize a lot of things!
?>
EOF
}

gen_empty_config() {
if [ -f $CONFIG_FILE ] ; then
	mv -f $CONFIG_FILE $CONFIG_FILE.back
fi

# Write the config file for b2evolution
cat > $CONFIG_FILE << EOF
<?php
/**
 * This is b2evolution's basic config file.
 *
 * You need to edit this file to your settings before attempting to install the database!
 * Last significant changes to this file: version 1.6
 *
 *
 * Reminder: every line starting with # or // is a comment, multiline comments are
 *           surrounded by '/*' and '* /' (without space).
 *
 * IMPORTANT: Take special care not to erase quotes (') around text parameters
 * and semicolums (;) at the end of the lines. Otherwise you'll get some
 * "unexpected T_STRING" parse errors!
 *
 * Contributors: you should override this file by creating a file named _config_TEST.php
 * (see end of this file).
 *
 * @package conf
 */
if( !defined('EVO_CONFIG_LOADED') ) die( 'Please, do not access this page directly.' );


// TODO: dh> this file was meant to be used for things where you only need the basic config..
// fp> also:
// - At least _admin.php should only be called when in the backoffice.
// - Also we should probably start by moving as many conf options to the backoffice as possible and see how much stuff is left in conf files
//    Note: some stuff does not make sense in the back-office (for example stuff that depends on the physical path where the files are installed)
// - In view of reorganization, please list (all or examples) of situations where only a subset of the conf should be loaded.


/**
 * Maintenance mode. Set this to 1 in order to temporarily disable access to the application.
 *
 * Note: it is still possible to access the install script during maintenance mode.
 */
\$maintenance_mode = 0;


// Below is an alternative hardcore version of maintenance mode.
// This one will block the install script too.
// Remove /* and */ to activate.
/*
header('HTTP/1.0 503 Service Unavailable');
echo '<h1>503 Service Unavailable</h1>';
die( 'The site is temporarily down for maintenance.' );
*/


/**#@+
 * MySQL DB settings.
 * Fill in your database details (check carefully or nothing will work!)
 */
\$db_config = array(
    'user'          => '<db_user>',        // your MySQL username
    'password'      => '<db_password>',    // ...and password
    'name'          => '<db_name>',        // the name of the database
    'host'          => 'localhost',        // MySQL Server (typically 'localhost')
);
/**#@-*/


/**
 * the tables prefix (gets placed before each b2evo table name),
 * use this to have multiple installations in one DB.
 *
 * @global string $tableprefix
 */
\$tableprefix = 'evo_';


/**
 * If you want to be able to reset your existing b2evolution tables and start anew
 * you must set $allow_evodb_reset to 1.
 *
 * NEVER LEAVE THIS SETTING ON ANYTHING ELSE THAN 0 (ZERO) ON A PRODUCTION SERVER.
 * IF THIS IS ON (1) AND YOU FORGET TO DELETE THE INSTALL FOLDER, ANYONE WOULD BE ABLE TO
 * ERASE YOUR B2EVOLUTION TABLES AND DATA BY A SINGLE CLICK!
 */
\$allow_evodb_reset = 0;	// Set to 1 to enable. Do not leave this on 1 on production servers


/**
 * $baseurl is where your blogs reside by default. CHECK THIS CAREFULLY or nothing will work.
 * It should be set to the URL where you can find the blog templates and/or the blog stub files,
 * that means index.php, blog_b.php, etc.
 * Note: Blogs can be in subdirectories of the baseurl. However, no blog should be outside
 * of there, or some tricky things may fail (e-g: pingback)
 *
 * IMPORTANT: If you want to test b2evolution on your local machine, do NOT use that machine's
 * name in the $baseurl!
 * For example, if your machine is called HOMER, do not use http://homer/b2evolution/blogs/ !
 * Use http://localhost/b2evolution/blogs/ instead. And log in on localhost too, not homer!
 * If you don't, login cookies will not hold.
 *
 * @global string $baseurl
 */
\$baseurl = '$BASE_URL';
// Use the following if you want to use the current domain:
/*
if( isset(\$_SERVER['HTTP_HOST']) )
{	// This only works if HOSt provided by webserver (i-e DOES NOT WORK IN PHP CLI MODE)
	\$baseurl = ( (isset(\$_SERVER['HTTPS']) && ( \$_SERVER['HTTPS'] != 'off' ) ) ?'https://':'http://')
							.\$_SERVER['HTTP_HOST'].'/';
}
*/

/**
 * This is used only to create the Admin account.
 * @todo move to installer.
 */
\$admin_email = 'postmaster@$DOMAIN';


/**
 * Once you have edited this file to your settings, set the following to 1 (one):
 */
\$config_is_done = 0;


# IMPORTANT: you will find more parameters in the other files of the /conf folder.
# IT IS RECOMMENDED YOU DO NOT TOUCH THOSE SETTINGS
# UNTIL YOU ARE FAMILIAR WITH THE DEFAULT INSTALLATION.
#
# It is however strongly recommended you browse through these files as soon as you've
# got your basic installation working. They'll let you customize a lot of things!
?>
EOF
}



create_db() {
# Create the database and user
# b2evolution's php install script will create the tables
    mysql --defaults-extra-file=/etc/mysql/debian.cnf <<EOF
CREATE DATABASE \`$DB_NAME\`;
GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,ALTER
ON \`$DB_NAME\`.*
TO $DB_USER@localhost
IDENTIFIED BY '$DB_PASSWORD';
FLUSH PRIVILEGES;
EOF
}

backup_db() {
    DATE=`date '+%j-%Y%m%d-%H%M%S'`
    BACKUP_DIR=/var/cache/b2evolution
    mkdir -p $BACKUP_DIR
    BACKUPFILE=$BACKUP_DIR/backup-$DB_NAME-$DATE.sql
    mysqldump --defaults-extra-file=/etc/mysql/debian.cnf --add-drop-table --add-drop-database -B $DB_NAME > $BACKUPFILE && echo Wrote $BACKUPFILE
}

get_old_db_user() {
    awk '/DB_USER/ {print $3}' $OLD_CONFIG_FILE |sed "s/^'//" |sed "s/'$//"
}

get_old_db_password() {
    awk '/DB_PASSWORD/ {print $3}' $OLD_CONFIG_FILE |sed "s/^'//" |sed "s/'$//"
}

get_old_db_name() {
    awk '/DB_NAME/ {print $3}' $OLD_CONFIG_FILE |sed "s/^'//" |sed "s/'$//"
}

get_old_base_url() {
    awk '/\$baseurl\ *=/ {print $3}' $OLD_CONFIG_FILE |sed "s/^'//" |sed "s/'\ *;$//"
}

get_old_admin_email() {
    awk '/\$admin_email\ *=/ {print $3}' $OLD_CONFIG_FILE |sed "s/^'//" |sed "s/'\ *;$//"
}

upgrade_db() {
    DATE=`date '+%j-%Y%m%d-%H%M%S'`
    UPGRADE_LOG_FILE=/var/cache/b2evolution/upgrade-$DB_NAME-$DATE.log
    UPGRADE_DB_SQL_SCRIPT=/usr/share/b2evolution/extras/b2evo_upgrade_092_to_241.sql
    echo 'Upgrading database schema (this can take some time)...'
    mysql --defaults-extra-file=/etc/mysql/debian.cnf -v -v $DB_NAME < $UPGRADE_DB_SQL_SCRIPT > $UPGRADE_LOG_FILE && echo "Done. A log file has been generated: $UPGRADE_LOG_FILE"
}

destroy_db() {
mysql --defaults-extra-file=/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 \`$DB_NAME\`;
EOF
}

while getopts "euhbd-" opt ; do
    case "$opt" in
	h) usage ; exit 0 ;;
	b) BACKUP=1  ;;
	d) DESTROY=1 ;;
	e) EMPTY=1   ;;
	u) UPGRADE=1 ;;
	-) 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

DB_USER="b2evolution"
DOMAIN="$1"
BASE_URL="$2"
DB_NAME="$3"

CONFIG_FILE="/etc/b2evolution/_basic_config.php"
OLD_CONFIG_FILE="/etc/b2evolution/_config.php"

if [ $DESTROY ] ; then
    destroy_db
    exit 0
fi

if [ $BACKUP ] ; then
    backup_db
    exit 0
fi

if [ $EMPTY ] ; then
    echo "Now generating empty config..."
    gen_empty_config
    exit 0
fi


if [ $UPGRADE ] ; then
    echo "Now Upgrading configuration..."
    OLD_DB_USER=`get_old_db_user`
    OLD_DB_PASSWORD=`get_old_db_password`
    OLD_DB_NAME=`get_old_db_name`
    #add ending slash to old baseurl, as required by b2evo 2.4.1 version.
    OLD_BASE_URL=`get_old_base_url`/
    OLD_ADMIN_EMAIL=`get_old_admin_email`
    gen_config
    DB_NAME=$OLD_DB_NAME
    backup_db
    upgrade_db
    exit 0
fi

if [ -z $DOMAIN ] || [ -z BASE_URL ] || [ -z DB_NAME ] ; then
    usage
    exit 1
fi

# else
gen_config
#create db only in case of a fresh package installation, and not an uprade.
create_db

