#!/bin/bash
set -e
trap "echo [$(date)] An ERROR occurred. Aborting." ERR

# Addresses of the cloudformation and helm templates to be used
CHART=s3://robotic-drive-analyzer-documentation/resources/rda-notebook-0.1.7.tgz
TYPE_ACTIVATION_TEMPLATE=https://robotic-drive-analyzer-documentation.s3.eu-central-1.amazonaws.com/resources/typeActivationAndRoleCreation.template
ANALYZER_TEMPLATE=https://robotic-drive-analyzer-documentation.s3.eu-central-1.amazonaws.com/resources/serviceAccountAndDeployment.template

# Specify the address of the image to be used
REGISTRY=709825985650.dkr.ecr.us-east-1.amazonaws.com
REPOSITORY=dxc-technology/robotic-drive-analyzer
IMAGE=rda_1.16_java_1.8_spark_3.1.2_python_3.7_v0.0.2

# Add optional config file specified on command line
if [[ -n "$1" ]]; then
  echo "[$(date)] Reading configuration variables from '$1' ..."
  . "$1"
else
  echo "[$(date)] Error: Please provide a configuration file - (template: https://robotic-drive-analyzer-documentation.s3.eu-central-1.amazonaws.com/resources/analyzer.conf)"
  exit 1
fi

if [[ -z "$AWS_REGION" ]]
then
  echo "[$(date)] Error: AWS_REGION should be specified"
  exit 1
fi

if [[ -z "$AWS_ACCOUNT_ID" ]]
then
  echo "[$(date)] Error: AWS_ACCOUNT_ID should be specified"
  exit 1
fi

if [[ -z "$CLUSTER_NAME" ]]
then
  echo "[$(date)] Error: CLUSTER_NAME should be specified"
  exit 1
fi

if [[ -z "$NAMESPACE" ]]
then
  echo "[$(date)] Error: NAMESPACE should be specified"
  exit 1
fi

# Check whether the cluster is already existing
if ! aws eks describe-cluster --name "${CLUSTER_NAME}" >/dev/null 2>&1
then
  echo "[$(date)] EKS cluster '${CLUSTER_NAME}' does not exist. Please make sure that the correct name is specified and the cluster is available."
  exit 1
fi

# Add eksctl if not present
if ! command -v eksctl &> /dev/null
then
  echo "[$(date)] eksctl not found, installing ..."
  curl --silent --location "https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz" | tar xz -C /tmp
  sudo mv /tmp/eksctl /usr/local/bin
fi

echo "[$(date)] Checking existing type activations"
for row in $(aws cloudformation list-types --visibility PRIVATE | jq -r '.TypeSummaries[].TypeName'); do
  if [[ "$row" == "AWSQS::Kubernetes::Helm" ]]
  then
    AWSQS_HELM_ROLE=$(aws cloudformation describe-type --type-name AWSQS::Kubernetes::Helm --type RESOURCE | jq -r ".ExecutionRoleArn")
    echo "[$(date)] Preexisting type activation for AWSQS::Kubernetes::Helm with role ${AWSQS_HELM_ROLE}."
    echo "[$(date)] Please ensure that the role has the permissions described in:"
    echo "[$(date)] https://github.com/aws-quickstart/quickstart-kubernetes-resource-provider/blob/main/execution-role.template.yaml"
    echo "[$(date)] Adding execution role to cluster's aws-auth"
    eksctl create iamidentitymapping --region ${AWS_REGION} --cluster ${CLUSTER_NAME}  --arn ${AWSQS_HELM_ROLE} --group system:masters --username admin
  elif [[ "$row" == "AWSQS::Kubernetes::Resource" ]]
  then
    AWSQS_RESOURCE_ROLE=$(aws cloudformation describe-type --type-name AWSQS::Kubernetes::Resource --type RESOURCE | jq -r ".ExecutionRoleArn")
    echo "[$(date)] Preexisting type activation for AWSQS::Kubernetes::Resource with role ${AWSQS_RESOURCE_ROLE}."
    echo "[$(date)] Please ensure that the role has the permissions described in:"
    echo "[$(date)] https://github.com/aws-quickstart/quickstart-kubernetes-resource-provider/blob/main/execution-role.template.yaml"
    echo "[$(date)] Adding execution role to cluster's aws-auth"
    eksctl create iamidentitymapping --region ${AWS_REGION} --cluster ${CLUSTER_NAME}  --arn ${AWSQS_RESOURCE_ROLE} --group system:masters --username admin
  fi
done

echo "[$(date)] Deploying the Robotic Drive Analyzer to EKS Cluster: ${CLUSTER_NAME}. This may take several minutes."
echo "[$(date)] The stack creates the following resources:"
if [[ -z "$AWSQS_RESOURCE_ROLE" ]] || [[ -z "$AWSQS_HELM_ROLE" ]]
then
  echo "[$(date)] - IAM role for type activations: arn:aws:iam::${AWS_ACCOUNT_ID}:role/${IAM_ROLE_NAME}"
  eksctl create iamidentitymapping --region ${AWS_REGION} --cluster ${CLUSTER_NAME}  --arn "arn:aws:iam::${AWS_ACCOUNT_ID}:role/${IAM_ROLE_NAME}" --group system:masters --username admin
fi

if [[ -z "$AWSQS_RESOURCE_ROLE" ]]
then
  echo "[$(date)] - Type activation: AWSQS::Kubernetes::Resource with Execution- and Log-role arn:aws:iam::${AWS_ACCOUNT_ID}:role/${IAM_ROLE_NAME}"
  AWSQS_RESOURCE_ROLE=false
fi

if [[ -z "$AWSQS_HELM_ROLE" ]]
then
  echo "[$(date)] - Type activation: AWSQS::Kubernetes::Helm with Execution- and Log-role arn:aws:iam::${AWS_ACCOUNT_ID}:role/${IAM_ROLE_NAME}"
  AWSQS_HELM_ROLE=false
fi
echo "[$(date)] - IAM Role for a Kubernetes Service Account with S3 full access"
echo "[$(date)] - Lambda function to determine the cluster's OIDC provider url"
echo "[$(date)] - Kubernetes Service Account in namespace ${NAMESPACE}: ${SERVICE_ACCOUNT_NAME}"
echo "[$(date)] - DXC Robotic Drive Analyzer Deployment in namespace ${NAMESPACE}: ${DEPLOYMENT_NAME}"
echo "[$(date)] - PySpark Python Packages: ${PYTHON_PACKAGES}"
aws cloudformation create-stack \
    --region ${AWS_REGION} \
    --stack-name ${STACK_NAME} \
    --capabilities CAPABILITY_NAMED_IAM \
    --template-url ${TYPE_ACTIVATION_TEMPLATE} \
    --parameters ParameterKey=AWSQSTypeActivationRole,ParameterValue=${IAM_ROLE_NAME} \
                ParameterKey=AdminPassword,ParameterValue=${ADMIN_PASSWORD} \
                ParameterKey=EKSClusterName,ParameterValue=${CLUSTER_NAME} \
                ParameterKey=Namespace,ParameterValue=${NAMESPACE} \
                ParameterKey=Chart,ParameterValue=${CHART} \
                ParameterKey=AnalyzerImageRegistry,ParameterValue=${REGISTRY} \
                ParameterKey=AnalyzerImageRepo,ParameterValue=${REPOSITORY} \
                ParameterKey=AnalyzerImageTag,ParameterValue=${IMAGE} \
                ParameterKey=AnalyzerStackTemplateUrl,ParameterValue=${ANALYZER_TEMPLATE} \
                ParameterKey=AWSQSResourceRole,ParameterValue=${AWSQS_RESOURCE_ROLE} \
                ParameterKey=AWSQSHelmRole,ParameterValue=${AWSQS_HELM_ROLE} \
                ParameterKey=ServiceAccountName,ParameterValue=${SERVICE_ACCOUNT_NAME} \
                ParameterKey=DeploymentName,ParameterValue=${DEPLOYMENT_NAME} \
                ParameterKey=PythonPackages,ParameterValue=\""${PYTHON_PACKAGES}"\"


# Await the successful creation of the stack
aws cloudformation wait stack-create-complete --stack-name ${STACK_NAME}
echo "[$(date)] Completed ${STACK_NAME}."
echo "[$(date)] The notebook can now be accessed by port-forwaring using the following command:"
echo "[$(date)] kubectl -n ${NAMESPACE} port-forward svc/${DEPLOYMENT_NAME}-zeppelin-svc 8080:8080"
