#!/bin/bash

CHRBIN=/usr/sbin/chroot
CHRD=/chroot/admin
DCHRD=/chroot/maild


if ! [ -x /usr/bin/makepasswd ]; then
    echo "Error: makepasswd package not installed!"
    exit 7
fi

if ! [ -x /usr/bin/mysql ]; then
    echo "Error: mysql package not installed!"
    exit 7
fi


makepass() {
    echo $(makepasswd --chars=16)
}

# exec sql query in admin chroot
exec_sql_chr()
{

    if [ $# -lt 1 -o $# -gt 2 ]; then
	echo "Programing error!"
	exit 200
    fi

    if [ $# -eq 1 ]; then
	CHRCMD=""
    else
	CHRDIR=$2

	if ! [ -d $CHRDIR ]; then
	    echo "Chroot $CHRDIR doesn't exist!"
	    exit 201
	fi
	CHRCMD="$CHRBIN $CHRDIR"
    fi

$CHRCMD mysql --defaults-file=/etc/mysql/debian.cnf -ss -n <<STOP
$1
\q
STOP

    if [ $? -ne 0 ] ; then  echo "SQL job failed: $1" >&2
	exit 131
    fi
}

# -----------------------------------------------------

# -----------
# sanity check

if [ "$1" != "SURE" ]; then
    echo "WARNING! This script will overwrite cluebringer mysql passwords."
    echo "If you are sure, type SURE as parameter"
    echo "Usage: reset-mysqlpw-cluebringer [SURE]"
    exit 7
fi


# -----------------------------------------------------

# changing root and debian_sys_maint passwords
cbpasswd=$(makepass)

echo "Resetting cluebringer mysql password..."

exec_sql_chr "SET PASSWORD FOR 'sys_cluebringer'@'localhost' = PASSWORD('$cbpasswd');" $CHRD
exec_sql_chr "flush privileges;" $CHRD

# admin chroot
sed -i "s/DB_PASS=\".*\";/DB_PASS=\"$cbpasswd\";/" $CHRD/etc/cluebringer/cluebringer-webui.conf

# maild chroot
sed -i "s/^Password=.*\$/Password=$cbpasswd/" $DCHRD/etc/cluebringer/cluebringer.conf

echo "new cluebringer password: $cbpasswd"
echo ""

/etc/init.d/postfix-cluebringer-chroot restart
