#!/bin/bash

NAME=0
USER=0
ID=0
PASS_SET=0

# Make sure we have the user and password
while getopts ":i:u:p:" opt; do
    case $opt in
        i)
            ID=1
            USER=$OPTARG
            ;;
        u)
            NAME=1
            USER=$OPTARG
            ;;
        p)
            PASS_SET=1
            PASS=$OPTARG
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            ;;
    esac
done

if [ $PASS_SET -eq 0 ] || [ $ID -eq 0 -a $NAME -eq 0 ]; then
    echo "Usage: $0 (-u <username> | -i <user_id>) -p <newpassword>"
    echo "This script resets a specified user's password."
    exit 1
fi

BASEDIR=$(dirname $(readlink -f $0))

# Import data
eval $(php $BASEDIR/import_fusionconfig.php)

# Create SQL file (so that it doesn't show up in the history)
if [ -f file1 ]; then
    rm file1
fi
echo "update users set password='" >> file1
php -r  "echo hash('sha256', '$PASS');" >> file1

if [[ $ID == 1 ]]; then
    echo "' where user_id='$USER';" >> file1
else
    echo "' where username='$USER';" >> file1
fi

tr -d '\n' < file1 > file2
echo "" >> file2
rm file1

# Execute SQL
mysql -h $cfg__database__fusion__host -u $cfg__database__fusion__user --password="$cfg__database__fusion__pass" $cfg__database__fusion__dbname < file2
rm file2

echo "Password for $USER set successfully"
echo ""