#!/usr/bin/env bash

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}")
image_registry=$(yq '.imageRegistry' "${local_config}")

dnsName=$(yq '.jobOptions.dataplaneManager.dnsName' "${local_config}")
hostedZone=$(yq '.jobOptions.dataplaneManager.hostedZone' "${local_config}")
dnsRecordName="${dnsName%.$hostedZone}"

timeout=${JOB_TIMEOUT:=300} # 5min
interval=${JOB_CHECK_INTERVAL:=10}
start_time=$(date +%s)
kong_svc=kong-kong-proxy
while [[ $(($(date +%s) - $start_time)) -lt $timeout ]]; do
  hostname=$(kubectl -n kong get svc "${kong_svc}" -ojsonpath='{.status.loadBalancer.ingress[0].hostname}')
  if [[ -z "$hostname" ]]; then
    sleep "${interval}"
  else
    echo "loadbalaner $hostname is ready"
    break
  fi
done
if [[ -z "$hostname" ]]; then
  echo "failed to get elb dns name"
  exit 1
fi

existedId=$(aliyun alidns DescribeDomainRecords \                                                                                                    .python3 09:23:36
  --DomainName $hostedZone \
  --KeyWord $dnsRecordName \
  --SearchMode EXACT \
  --Type CNAME \
  | jq '.DomainRecords.Record[0].RecordId // ""')
if [[ -z "$existedId" ]]; then
  aliyun alidns AddDomainRecord \
    --DomainName $hostedZone \
    --RR $dnsRecordName \
    --Type CNAME \
    --Value $hostname
else
  aliyun alidns UpdateDomainRecord \
    --RecordId "$existedId" \
    --RR $dnsRecordName \
    --Type CNAME \
    --Value $hostname
fi
if [[ $? -ne 0 ]];  then
  echo "failed to update dns record"
  exit 1
fi

while [[ $(($(date +%s) - $start_time)) -lt $timeout ]]; do
  nslookup "${dnsName}"
  if [[ $? -ne 0 ]];  then
    sleep "${interval}"
  else
    echo "$dnsName is ready"
    exit 0
  fi
done
exit 1 # DNS not ready