#!/bin/bash

## Writes the zone CA of the given account to a file.

API_ENDPOINT="https://ccm.fortanix.com/v1"
OUTPUT_FILE="ca.pem"

CURL="$(command -v curl)"
curl() {
  $CURL -k -sS -H "Content-Type: application/json" -c "$cookie_path" -b "$cookie_path" -H "X-CSRF-Header:true" "$@"
  echo
}

printf "Email: " 1>&2
read ACCOUNT_EMAIL

stty -echo
printf "Password: " 1>&2
read ACCOUNT_PASSWORD
stty echo

echo 1>&2

printf "Account name: " 1>&2
read ACCOUNT_NAME


# authentication
cookie_path=$(mktemp -p "/tmp" -t "cookiejar.XXXXX")
output=$(curl -X POST -u "$ACCOUNT_EMAIL:$ACCOUNT_PASSWORD" "$API_ENDPOINT/sys/auth")

# select account
output=$(curl "$API_ENDPOINT/accounts")
account_id=$(echo "$output" | jq -r '.items | .[] | select(.name=="'"$ACCOUNT_NAME"'") | .acct_id')
output=$(curl -X POST "$API_ENDPOINT/sys/session/select_account/$account_id")

# get certificate and write it to a file
output=$(curl -X GET "$API_ENDPOINT/zones")
output=$(echo "$output" |  jq -r '.[] | select(.acct_id=="'"$account_id"'") | .certificate' | awk 'NF')

if [[ $output == *"BEGIN CERTIFICATE"* ]]; then
  echo "$output" > $OUTPUT_FILE
  echo "Certificate saved in '$OUTPUT_FILE'"
  exit 0
fi

echo "Could not get certificate"
exit 1