#!/usr/bin/env bash
prefix=${1:-seed}

ROOT=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)
source "${ROOT}/lib.sh"

remote_config=${CONFIG_PATH}
local_config=/tmp/base-config.yaml

output_bucket_endpoint=$(get_oss_bucket_endpoint "$remote_config")
aliyun oss cp "${remote_config}" "${local_config}" --endpoint=$output_bucket_endpoint -f

argocd_repo=tidbcloud/app-delivery
region=$(yq '.region' "${local_config}")
env=$(yq '.env' "${local_config}")
cloud=$(yq '.cloudProvider' "${local_config}")
cluster=$(yq '.k8s.name' "${local_config}")
jobId=$(yq '.jobId' "${local_config}")
output=$(yq '.outputPath' "${local_config}")

regionName=$(yq '.name' "${local_config}")
k8sEndpoint=$(yq '.k8s.endpoint' "${local_config}")
controlplane_account=$(yq '.alicloud.controlplaneAccount' "${local_config}")
profileName=$(yq '.jobOptions.jumpServer.profileName' "${local_config}")
enableRegister=$(yq '.jobOptions.jumpServer.enabled' "${local_config}")

if [[ $enableRegister == "null" || $enableRegister == "false" ]]; then
  echo "Disable to register jump server destination"
  exit 0
fi

jumpServerEnv=$(yq ".jobOptions.jumpServer.env // \"$env\"" "${local_config}")
cluster_id=$(get_cluster_id "$cluster")

# support $env $region as part of prefix
prefix=$(eval "echo $prefix")
name="$prefix-${regionName}"
destination=$(cat <<EOF
type: controlplane
name: $name
k8sName: $cluster
k8sEndpoint: $k8sEndpoint
alicloudAuth:
  clusterID: ${cluster_id}
  profileName: ${profileName}
EOF
)

# Deploy application services by invoking deploy-new-region action in $argocd_repo
common_params="-f env=${jumpServerEnv} -f jobId=${jobId}"
export GH_REPO="${argocd_repo}"
gh workflow run new-jump-server-dst.yaml ${common_params} -f name="${name}" -f destination="${destination}"

kubectl apply -f - <<EOF
apiVersion: ramauthenticator.k8s.alibabacloud/v1alpha1
kind: RAMIdentityMapping
metadata:
  name: jump-service
spec:
  # The created role arn.
  arn: 'acs:ram::${controlplane_account}:role/jump-service-role'
  username: jump-service
  groups:
    - system:masters
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: jump-service-clusterrolebinding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cs:admin
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: jump-service
EOF
