#!/usr/bin/env bash

set -euo pipefail

cd "$(dirname "$0")/../../" # Navigate to the root of the project

target="${1:-aws}"

if [ "$target" == "aws" ] ; then
    aws sso login --profile base
elif [ "$target" == "m2m" ] ; then
    ENCODED_SECRET=$(echo -n $COGNITO_CLIENT_ID:$COGNITO_CLIENT_SECRET | base64 -w 0)
    token=$(\
        curl -s -X POST $COGNITO_TOKEN_ENDPOINT_URL \
            -H 'Content-Type: application/x-www-form-urlencoded' \
            -H "Authorization: Basic ${ENCODED_SECRET}" \
            -d 'grant_type=client_credentials' \
            -d "aws_client_metadata={\"callerService\":\"ctm\", \"tenantName\":\"${COGNITO_CLIENT_TENANT_NAME}\"}" | jq . \
    )
    echo $token
elif [ "$target" == "local-user" ] ; then
    POOL_ID=$(aws cognito-idp list-user-pools --profile local --max-results 1 --query "UserPools[?Name==\`${LOCAL_MANAGEMENT_USER_POOL_NAME}\`].Id" --output text)
    CLIENT_ID=$(aws cognito-idp list-user-pool-clients --profile local --user-pool-id "$POOL_ID" --query 'UserPoolClients[0].ClientId' --output text)
    token=$(aws cognito-idp admin-initiate-auth \
        --profile local \
        --user-pool-id "$POOL_ID" \
        --client-id "$CLIENT_ID" \
        --auth-flow ADMIN_USER_PASSWORD_AUTH \
        --auth-parameters USERNAME=${LOCAL_COGNITO_ADMIN_USERNAME:?},PASSWORD=${LOCAL_COGNITO_ADMIN_PASSWORD:?} \
        --query 'AuthenticationResult.IdToken' --output text)
    echo $token
else
    echo "Unsupported target: $target"
    exit 1
fi
