#!/usr/bin/bash
#
# Create a MySQL/PostgreSQL database for a SmartOS VM.
# Copyright (c) 2016 Joyent Inc., All rights reserved.

set -o errexit
set -o pipefail
#set -o nounset
#set -o xtrace

usage() {
        cat <<- EOF >&2

Usage: $0 [options] TYPE DATABASE

Arguments:
    
    TYPE             Type of database: mysql or postgresql.
    DATABASE         Name of database you want to create.

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 [[ $# = 2 ]]; then
	DB_TYPE=$1;
	DB_NAME=$2;
else
	usage;
fi

export LANG=C
PATH="/opt/local/bin:/opt/local/gnu/bin:/opt/local/sbin:/usr/bin:/usr/sbin";

create_mysqldb() {
	hash mysql 2>/dev/null || { echo "* ERROR - mysql was not found in your PATH." && exit 2; }

	[[ ! `pgrep mysqld` ]] && echo "* ERROR - mysql must be running to create a database." && exit 2;

        mysql -u${DB_USER} -p${DB_PASS} -e "select version();" > /dev/null 2>&1 || \
                { echo "* ERROR - Can't connect with username password specified." && exit 2; }

        [[ $(mysql -u${DB_USER} -p${DB_PASS} -e "use ${DB_NAME};" &>/dev/null)$? -eq 1 ]] || \
                { echo "* ERROR - Database ${DB_NAME} already exists." && exit 2; }

	mysql -u${DB_USER} -p${DB_PASS} -e "create database ${DB_NAME};" > /dev/null 2>&1 || \
		{ echo "* ERROR - There was an error creating your database." && exit 2; }

	echo "* Created MySQL database ${DB_NAME}.";
}
create_postgresdb() {
	hash psql 2>/dev/null || { echo "* ERROR - psql was not found in your PATH." && exit 2; }

	export PGPASSWORD=${DB_PASS};

        [[ ! `pgrep postgres` ]] && echo "* ERROR - postgresql must be running to create a database." && exit 2;

        psql -U ${DB_USER} -c "select datname from pg_database;" > /dev/null 2>&1 || \
 		{ echo "* ERROR - Can't connect with username password specified." && exit 2; }

	[[ $(psql -U ${DB_USER} --list | egrep "\b${DB_NAME}\b") ]] && echo "* ERROR - Database ${DB_NAME} already exists." && exit 2;

	psql -U ${DB_USER} -c "create database ${DB_NAME};" > /dev/null 2>&1 || \
		{ echo "* ERROR - There was an error creating your database." && exit 2; }

	echo "* Created PostgreSQL database ${DB_NAME}.";
}

case $DB_TYPE in
	mysql)
		DB_USER=${DB_USER:-root};
		DB_PASS=${DB_PASS:-$(mdata-get mysql_pw 2> /dev/null)} || DB_PASS="null";
		create_mysqldb;
		;;
	postgresql)
		DB_USER=${DB_USER:-postgres};
		DB_PASS=${DB_PASS:-$(mdata-get pgsql_pw 2> /dev/null)} || DB_PASS="null";
		create_postgresdb;
		;;
	*)
		usage;
		;;
esac
