#!/bin/sh

PASSWORD=''
CLIENT_ID=''
AUTORITIES=''

while [ $# -ne 0 ]
do
    case "$1" in
        -h)
            cat << EOF
usage: $0 [-c CLIENT_ID]  [-a AUTHORITIES] [password]
EOF
            exit
            ;;
        -c)
            CLIENT_ID=$2
            shift
            ;;
        -a)
            AUTHORITIES=$2
            shift
            ;;
        *)
            if [ "x$PASSWORD" != "x" ]; then
                usage
                echo "you have already provided a password"
            fi
            PASSWORD=$1
            ;;
    esac
    shift
done

if [ "x$PASSWORD" = "x" ]; then
    #ask for a password
    HASHED_PASSWORD=`htpasswd -nBC 12 "" | tr -d ':\n'`
else
    #use the password provided by command line
    HASHED_PASSWORD=`htpasswd -bnBC 12 "" $PASSWORD | tr -d ':\n'`
fi


if [ "x$CLIENT_ID" = "x" ]; then
    echo $HASHED_PASSWORD
else
    if [ "x$AUTHORITIES" = "x" ]; then
        cat << EOF
-- This SQL script will update an OAuth client details record with a new password.
UPDATE oauth_client_details
SET client_secret = '$HASHED_PASSWORD'
WHERE client_id = '$CLIENT_ID';
EOF
else
    cat << EOF
-- This SQL script will insert a new OAuth client details record.

INSERT INTO oauth_client_details(client_id, client_secret, scope, authorized_grant_types, authorities)
VALUES ('$CLIENT_ID', '$HASHED_PASSWORD', 'api', 'client_credentials', '$AUTHORITIES');
EOF
    fi
fi
