#!/bin/bash

set -euo pipefail

usage() {
    cat <<'EOF'
Usage: daylily-return-fsx-filesystem-for-cluster <cluster_name> <region>

Print FSx filesystem ids and current Data Repository Associations for a cluster.

Environment:
  AWS_PROFILE  AWS CLI profile to use
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
    usage
    exit 0
fi

CLUSTER_NAME="${1:-}"
REGION="${2:-}"
AWS_PROFILE="${AWS_PROFILE:-}"

if [[ -z "$CLUSTER_NAME" || -z "$REGION" || -z "$AWS_PROFILE" ]]; then
    usage
    exit 1
fi

if ! command -v aws >/dev/null 2>&1; then
    echo "Error: required command 'aws' not found in PATH" >&2
    exit 1
fi

# Get FSx IDs associated with the cluster
FSX_IDS=$(aws fsx describe-file-systems \
    --profile "$AWS_PROFILE" \
    --region "$REGION" \
    --query "FileSystems[?contains(Tags[?Key=='parallelcluster:cluster-name'].Value | [0], '$CLUSTER_NAME')].FileSystemId" \
    --output text)
 

echo "FSx IDs associated with cluster '$CLUSTER_NAME':" >&2
echo "$FSX_IDS"

for fsx_id in $FSX_IDS; do
    echo "Data Repository Associations for $fsx_id:" >&2
    aws fsx describe-data-repository-associations \
        --profile "$AWS_PROFILE" \
        --region "$REGION" \
        --filters Name=file-system-id,Values="$fsx_id" \
        --query "Associations[].{AssociationId:AssociationId,FileSystemPath:FileSystemPath,DataRepositoryPath:DataRepositoryPath,Lifecycle:Lifecycle}" \
        --output table
done
