#!/bin/bash
#sudo apt install sshpass


for Gmail in $(gcloud auth list --filter=ACTIVE:*  --format="value(ACCOUNT)")
do
    echo "$Gmail"
    #echo ${Gmail%@*}
    gcloud config set account $Gmail
    for billing_ID in $(gcloud beta billing accounts list --filter=OPEN:True --format="value(ACCOUNT_ID)")
    do
        echo "$billing_ID"
        for project in $(gcloud beta billing projects list --billing-account=$billing_ID --filter=BILLING_ENABLED:True --format="value(projectId)")
        do
            echo "ProjectId:  $project"
            gcloud config set project $project
            projectname=`gcloud projects describe "$project" --format="value(name)"`
	    echo "projectname: $projectname"
            #a=`gcloud iam service-accounts list|grep "EMAIL: "
            serviceaccount=`gcloud iam service-accounts list --filter=DISABLED:False --format="value(EMAIL)" --limit=1`
	    echo "serviceaccount: $serviceaccount"
            #serviceaccount="${a/EMAIL: /}"
            filename1=$Gmail"-"$project"-"$projectname
            filename="${filename1/ /}"
            rm "$filename".json
            gcloud iam service-accounts keys create "./$filename".json --iam-account="$serviceaccount"
            #sshpass -p zCx5nZBeQIVS scp "./$filename".json azureuser@20.68.122.41:/home/azureuser/"$filename".json
        done
    done
done