#!/bin/sh

echo "Logging In..."
passdata="$(pass Internet/comdirect.com)"
client_id=$(echo "$passdata" | grep ^client_id | awk '{ print $2 }')
client_secret=$(echo "$passdata" | grep ^client_secret | awk '{ print $2 }')
username=$(echo "$passdata" | grep ^user | awk '{ print $2 }')
password=$(echo "$passdata" | head -1)

### FUNCTIONS
get_token() {
    token=$(curl -s \
        -X POST \
        -H "Accept:application/json" \
        -H "Content-Type:application/x-www-form-urlencoded" \
        --data-urlencode "client_id=$client_id" \
        --data-urlencode "client_secret=$client_secret" \
        --data-urlencode "username=$username" \
        --data-urlencode "password=$password" \
        --data-urlencode "grant_type=password" \
        https://api.comdirect.de/oauth/token \
        | jq -r .access_token)
    echo "$token"
}

# $1 token
get_session() {
    transactions=$(curl -s \
        -X POST \
        -H "Accept:application/json" \
        -H "Content-Type:application/x-www-form-urlencoded" \
        --data-urlencode "client_id=$client_id" \
        --data-urlencode "client_secret=$client_secret" \
        --data-urlencode "username=$username" \
        --data-urlencode "password=$password" \
        --data-urlencode "grant_type=password" \
        https://api.comdirect.de/ \
        | jq -r .access_token)
    echo "$transactions"

}

### MAIN PROGRAM
TOKEN=$(get_token)
echo "Got token: $TOKEN"
