#!/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

hongkong_host_key=$(cluster_ssh "$CLUSTER_HONGKONG_HOST" \
  "cut -d ' ' -f 1,2 /etc/ssh/ssh_host_ed25519_key.pub")
[[ $hongkong_host_key =~ ^ssh-ed25519\ [A-Za-z0-9+/]+={0,2}$ ]] || {
  echo 'invalid Hong Kong SSH host key' >&2
  exit 1
}
hongkong_host_key_b64=$(printf '%s' "$hongkong_host_key" | base64 | tr -d '\n')

public_key=$(cluster_ssh "$CLUSTER_NINGBO_HOST" 'bash -s' <<'REMOTE'
set -euo pipefail
install -d -m 0700 /root/.ssh
if [[ ! -f /root/.ssh/id_ed25519_easyai_cert_sync ]]; then
  ssh-keygen -q -t ed25519 -N '' -f /root/.ssh/id_ed25519_easyai_cert_sync
fi
cat /root/.ssh/id_ed25519_easyai_cert_sync.pub
REMOTE
)
[[ $public_key == ssh-ed25519\ * ]] || {
  echo 'invalid certificate sync public key' >&2
  exit 1
}
public_key_b64=$(printf '%s' "$public_key" | base64 | tr -d '\n')
cluster_ssh "$CLUSTER_HONGKONG_HOST" bash -s -- "$public_key_b64" <<'REMOTE'
set -euo pipefail
public_key=$(printf '%s' "$1" | base64 -d)
[[ $public_key == ssh-ed25519\ * ]]
install -d -m 0700 /root/.ssh
touch /root/.ssh/authorized_keys
chmod 0600 /root/.ssh/authorized_keys
sed -i '/^ssh-ed25519$/d' /root/.ssh/authorized_keys
grep -Fqx "$public_key" /root/.ssh/authorized_keys || printf '%s\n' "$public_key" >>/root/.ssh/authorized_keys
REMOTE

cluster_ssh "$CLUSTER_NINGBO_HOST" bash -s -- "$hongkong_host_key_b64" <<'REMOTE'
set -euo pipefail
hongkong_host_key=$(printf '%s' "$1" | base64 -d)
[[ $hongkong_host_key == ssh-ed25519\ * ]]
install -d -m 0700 /root/.ssh
known_hosts=/root/.ssh/known_hosts
temporary=$(mktemp /root/.ssh/known_hosts.XXXXXX)
if [[ -f $known_hosts ]]; then
  grep -Ev '^10\.77\.0\.2([ ,]|$)' "$known_hosts" >"$temporary" || true
fi
printf '10.77.0.2 %s\n' "$hongkong_host_key" >>"$temporary"
chmod 0600 "$temporary"
mv "$temporary" "$known_hosts"
REMOTE

cluster_scp "$script_dir/sync-nginx-certificate.sh" \
  "$CLUSTER_NINGBO_HOST:/usr/local/sbin/easyai-sync-nginx-certificate"
cluster_ssh "$CLUSTER_NINGBO_HOST" 'bash -s' <<'REMOTE'
set -euo pipefail
chmod 0750 /usr/local/sbin/easyai-sync-nginx-certificate
install -d -m 0755 /etc/letsencrypt/renewal-hooks/deploy
ln -sfn /usr/local/sbin/easyai-sync-nginx-certificate \
  /etc/letsencrypt/renewal-hooks/deploy/easyai-sync-nginx-certificate
/usr/local/sbin/easyai-sync-nginx-certificate
REMOTE
echo 'certificate_sync_install=PASS'
