#!/usr/bin/bash
#
# List MySQL/PostgreSQL database users 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

Usage: $0 [options] TYPE

Arguments:
    
    TYPE             Type of database: mysql or postgresql.

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

export LANG=C
PATH="/opt/local/bin:/opt/local/gnu/bin:/opt/local/sbin:/usr/bin:/usr/sbin";
ZONENAME=$(zonename);

list_mysqldbusers() {
        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 list the databases." && 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; }

	echo "* Listing MySQL users for ${ZONENAME}..";

	mysql -u${DB_USER} -p${DB_PASS} -s -e "select User,Host from mysql.user;" 2> /dev/null || \
		{ echo "* ERROR - There was an error listing the database users." && exit 2; }
}
list_postgresdbusers() {
        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 list the databases." && 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; }

	echo "* Listing PostgreSQL users for ${ZONENAME}..";

	psql -U ${DB_USER} -t -A -c 'select usename from pg_user;' 2> /dev/null || \
		{ echo "* ERROR - There was an error listing the database users." && exit 2; }
}

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