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

JD_HOST=${1:?JD host is required}

install -m 644 /tmp/guanghu-jd-authz-tunnel.service /etc/systemd/system/guanghu-jd-authz-tunnel.service
install -m 644 /tmp/guanghu-authz.nginx.conf /etc/nginx/snippets/guanghu-authz.conf
chmod 600 /etc/guanghu/secrets/ssh/bs_gz_006_to_jd_authz_proxy

install -m 600 /dev/null /etc/guanghu/jd-authz-tunnel-ssh-config
sed \
  -e "s/JD_PUBLIC_ADDRESS/${JD_HOST}/" \
  /tmp/jd-authz-tunnel-ssh-config.example > /etc/guanghu/jd-authz-tunnel-ssh-config

if ! grep -q "include /etc/nginx/snippets/guanghu-authz.conf;" /etc/nginx/sites-enabled/guanghulab; then
  sed -i '0,/server_name guanghulab.com;/s##server_name guanghulab.com;\n    include /etc/nginx/snippets/guanghu-authz.conf;#' /etc/nginx/sites-enabled/guanghulab
fi

systemctl daemon-reload
systemctl enable --now guanghu-jd-authz-tunnel.service
nginx -t
systemctl reload nginx

rm -f /tmp/guanghu-jd-authz-tunnel.service /tmp/guanghu-authz.nginx.conf /tmp/jd-authz-tunnel-ssh-config.example
