#!/bin/bash
#aws dev cluster name: centralized-storage-dev-regional-us-west-2
#aws dev cluster region: us-west-2
if [ -n "$1" ]
then
  clusterName=$1
else
  echo "cluster name is required in the first parameter, example:centralized-storage-dev-regional-us-west-2"
  exit
fi

if [ -n "$2" ]
then
  clusterRegion=$2
else
  echo "cluster region is required in the second parameter, example:  us-west-2"
  exit
fi


#k8s  serviceAccount info
accountName=vector
namespace=vector-agent

#aws role name
roleName=o11y-ft-write-${clusterRegion}
#aws current user  info
awsAccountID=$(aws sts get-caller-identity --query "Account" --output text)
#IAM OpenID Connect
oidcProvider=$(aws eks describe-cluster --name  $clusterName --region $clusterRegion --query "cluster.identity.oidc.issuer" --output text | sed -e "s/^https:\/\///")

cat > trust-relationship.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::$awsAccountID:oidc-provider/$oidcProvider"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringLike": {
          "$oidcProvider:aud": "sts.amazonaws.com",
          "$oidcProvider:sub": "system:serviceaccount:$namespace:*"
        }
      }
    }
  ]
}
EOF

echo "create-role start"
#create role
aws iam create-role --role-name $roleName --assume-role-policy-document file://trust-relationship.json --no-paginate > $roleName.json
#inline policy
aws iam put-role-policy --role-name $roleName --policy-name ft-write-policy-${clusterRegion} --policy-document file://aws_role_policy.json  --no-paginate
echo "create-role completed"
#deploy vector config and role
kubectl apply -f agent_common.yaml
#annotate
kubectl annotate serviceaccount -n $namespace $accountName eks.amazonaws.com/role-arn=arn:aws:iam::$awsAccountID:role/$roleName
#deploy vector
kubectl apply -f vector_aws.yaml

echo "deploy done"
