#!/usr/bin/env bash
set -euo pipefail

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=scripts/cluster/common.sh
source "$script_dir/common.sh"
load_cluster_env

cluster_ssh "$CLUSTER_NINGBO_HOST" \
  'install -d -m 0755 /usr/local/lib/easyai-ai-gateway-release /usr/local/share/easyai-ai-gateway-release/production'
cluster_scp "$cluster_root/deploy/kubernetes/easyai-ai-gateway-cluster-release" \
  "$CLUSTER_NINGBO_HOST:/usr/local/sbin/easyai-ai-gateway-cluster-release"
cluster_scp "$cluster_root/deploy/kubernetes/easyai-ai-gateway-cluster-release.conf.example" \
  "$CLUSTER_NINGBO_HOST:/usr/local/share/easyai-ai-gateway-release/easyai-ai-gateway-cluster-release.conf.example"
cluster_scp "$cluster_root/scripts/release-manifest.mjs" \
  "$CLUSTER_NINGBO_HOST:/usr/local/lib/easyai-ai-gateway-release/release-manifest.mjs"
for desired_state_file in \
  namespace.yaml service-account-rbac.yaml application-config.yaml application.yaml \
  database.yaml network-policy.yaml kustomization.yaml; do
  cluster_scp "$cluster_root/deploy/kubernetes/production/$desired_state_file" \
    "$CLUSTER_NINGBO_HOST:/usr/local/share/easyai-ai-gateway-release/production/$desired_state_file"
done
cluster_ssh "$CLUSTER_NINGBO_HOST" 'bash -s' <<'REMOTE'
set -euo pipefail
if [[ ! -e /etc/easyai-ai-gateway-cluster-release.conf ]]; then
  install -m 0640 \
    /usr/local/share/easyai-ai-gateway-release/easyai-ai-gateway-cluster-release.conf.example \
    /etc/easyai-ai-gateway-cluster-release.conf
fi
chmod 0750 /usr/local/sbin/easyai-ai-gateway-cluster-release
chmod 0640 /etc/easyai-ai-gateway-cluster-release.conf
chmod 0755 /usr/local/lib/easyai-ai-gateway-release/release-manifest.mjs
find /usr/local/share/easyai-ai-gateway-release/production -type f -exec chmod 0644 {} +
REMOTE
echo 'cluster_release_helper_install=PASS'
