#!/bin/bash

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


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 horde mysql passwords."
    echo "If you are sure, type SURE as parameter"
    echo "Usage: reset-mysqlpw-horde [SURE]"
    exit 7
fi


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

# changing root and debian_sys_maint passwords
hordepasswd=$(makepass)
adminmailpasswd=$(makepass)

echo "Resetting horde mysql passwords..."

exec_sql_chr "SET PASSWORD FOR 'sys_horde'@'localhost' = PASSWORD('$hordepasswd');" $CHRD
sed -i "s/\['sql'\]\['password'\] = '.*'/\['sql'\]\['password'\] = '$hordepasswd'/" $CHRD/etc/horde/horde/conf.php

exec_sql_chr "SET PASSWORD FOR 'sys_admin_mail'@'localhost' = PASSWORD('$adminmailpasswd');" $CHRD
sed -i -E "s/^[\t ]*'password'[\t ]*=>[\t ]*'.*?'[\t ]*,/\t'password' => '$adminmailpasswd',/" $CHRD/etc/horde/passwd/backends.php

exec_sql_chr "flush privileges;" $CHRD

echo "new horde password: $hordepasswd"
echo "new admin_mail password: $adminmailpasswd"
