#!/bin/bash

set -euo pipefail

# When changing this script, remember to modify the corresponding github action
vendor=${1}
env=${2}
region=${3}
logical_region=${4}

# Generate first_period as next month's first day at 00:00:00
first_period=$(date -d "$(date +%Y-%m-01) +1 month" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || date -v+1m -v1d -v0H -v0M -v0S '+%Y-%m-%d %H:%M:%S')

ROOT=$(cd $(dirname ${BASH_SOURCE[0]}) && pwd)

if [[ "$vendor" == "aws" || "$vendor" == "gcp" || "$vendor" == "alicloud" ]]; then
    deploy_dir="${ROOT}/envs/${env}-${vendor}-${logical_region}"
    deploy_file="${deploy_dir}/values.yaml"
    variant_dir="${ROOT}/variants/${vendor}"

    if [ -e ${deploy_dir} ]; then
      echo "New region deploy dir of metering server already exist, skip it"
    else
      mkdir -p ${deploy_dir}
      echo "Prepare manifest files"

      # Function to handle cross-platform sed compatibility
      sed_inplace() {
          if [[ "$OSTYPE" == "darwin"* ]]; then
              sed -i '' "$@"
          else
              sed -i "$@"
          fi
      }

      cp "${variant_dir}/values-tmpl.yaml" "${deploy_file}"
      sed_inplace "s|TMPL_REGION|${region}|g" "${deploy_file}"
      sed_inplace "s|TMPL_LOGICAL_REGION|${logical_region}|g" "${deploy_file}"
      sed_inplace "s|TMPL_FIRST_PERIOD|${first_period}|g" "${deploy_file}"
    fi
fi

