# Source this file in Bash: source ./authenticate.sh
nsis_login() {
    local nsis_username nsis_password nsis_totp nsis_response nsis_access nsis_refresh
    local -a nsis_totp_arg=()
    read -r -p 'NSIS username: ' nsis_username
    read -r -s -p 'NSIS password: ' nsis_password; printf '\n'
    read -r -s -p 'Current TOTP (leave empty only if your account does not require it): ' nsis_totp; printf '\n'
    if [[ -n "$nsis_totp" ]]; then
        nsis_totp_arg=(--data-urlencode "totp=$nsis_totp")
    fi
    nsis_response=$(curl --fail --silent --show-error \
        'https://identity.nsiscloud.polsa.gov.pl/auth/realms/NSIS-Cloud/protocol/openid-connect/token' \
        --data-urlencode 'client_id=nsis-public' \
        --data-urlencode 'grant_type=password' \
        --data-urlencode "username=$nsis_username" \
        --data-urlencode "password=$nsis_password" \
        "${nsis_totp_arg[@]}") || return 1
    nsis_access=$(jq -er '.access_token | select(type == "string" and length > 0)' <<< "$nsis_response") || return 1
    nsis_refresh=$(jq -er '.refresh_token | select(type == "string" and length > 0)' <<< "$nsis_response") || return 1
    export ACCESS_TOKEN="$nsis_access" REFRESH_TOKEN="$nsis_refresh"
    printf '%s\n' 'NSIS tokens are set in this shell.'
}
nsis_login
