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

domain=ai.51easyai.com
hongkong_host=${AI_GATEWAY_CERT_SYNC_HOST:-root@10.77.0.2}
identity_file=${AI_GATEWAY_CERT_SYNC_KEY:-/root/.ssh/id_ed25519_easyai_cert_sync}

[[ $(hostname -I) == *10.77.0.1* ]] || {
  echo 'certificate sync must run on the Ningbo node' >&2
  exit 1
}
[[ -f $identity_file && ! -L $identity_file ]] || {
  echo 'certificate sync SSH identity is unavailable' >&2
  exit 1
}

install -d -m 0700 "/etc/nginx/tls/$domain"
install -m 0644 "/etc/letsencrypt/live/$domain/fullchain.pem" \
  "/etc/nginx/tls/$domain/fullchain.pem"
install -m 0600 "/etc/letsencrypt/live/$domain/privkey.pem" \
  "/etc/nginx/tls/$domain/privkey.pem"
ssh -i "$identity_file" -o BatchMode=yes "$hongkong_host" \
  "install -d -m 0700 /etc/nginx/tls/$domain"
scp -q -i "$identity_file" -o BatchMode=yes \
  "/etc/nginx/tls/$domain/fullchain.pem" \
  "$hongkong_host:/etc/nginx/tls/$domain/fullchain.pem"
scp -q -i "$identity_file" -o BatchMode=yes \
  "/etc/nginx/tls/$domain/privkey.pem" \
  "$hongkong_host:/etc/nginx/tls/$domain/privkey.pem"
ssh -i "$identity_file" -o BatchMode=yes "$hongkong_host" \
  "chmod 0600 /etc/nginx/tls/$domain/privkey.pem && nginx -t && systemctl reload nginx"
nginx -t
systemctl reload nginx
echo 'certificate_sync=PASS'
