#!/bin/bash
if [ "$EDGE_SERVER" == "" ]; then
    export EDGE_SERVER="http://localhost:5324/"
fi

# Read
read -rp "Account username: " username
read -rsp "New password: " passwd
echo
echo

# Check
if ! command -v jq &>/dev/null ; then
    echo Installing missing tools...
    echo Please wait...
    if ! pacman -Sy jq --noconfirm &>/dev/null; then
         1>&2 echo Error: failed to install JQ
         1>&2 echo Error: please install JQ yourself before using this script
         exit 1
    fi
    echo Done! Ready!
    echo
fi

# Contact server
function edgeRequest() {
    curl -fs "$EDGE_SERVER/$1/$2" --data-binary "$3"
}
function json() {
    ret="{"
    first=true
    args=("$@")
    key=""
    for arg in "${args[@]}"; do
        if [ "$key" == "" ]; then
            key="$arg"
        else
            val="$arg"
            if [ "$first" != true ]; then
                ret+=","
            fi
            ret+="$(echo "$key" | jq -R)"
            ret+=":"
            ret+="$(echo "$val" | jq -R)"
            first=false
            key=""
        fi
    done
    ret+="}"
    echo "$ret"
}

# Get ID
echo Requesting user information...
resp="$(edgeRequest "accountmanager" "getAccountID" "$(json "username" "$username")")"
if [ "$?" != 0 ]; then
    1>&2 echo Error: contacting server failed
    exit 1
fi
success="$(echo "$resp" | jq .success -r)"
if [ "$success" != "true" ]; then
    1>&2 echo Error: server replied: account not recognized
    exit 1
fi
id="$(echo "$resp" | jq .id -r)"

# Send request
echo Sending password update...
resp="$(edgeRequest "accountmanager" "accounts/updatePassword" "$(json "id" "$id" "newPassword" "$passwd")")"
if [ "$?" != 0 ]; then
    1>&2 echo Error: contacting server failed
    exit 1
fi
success="$(echo "$resp" | jq .success -r)"
if [ "$success" != "true" ]; then
    1>&2 echo Error: server replied: password not valid
    exit 1
fi
echo
echo Password updated successfully.
