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

if [[ ${EUID} -ne 0 ]]; then
  echo "run as root" >&2
  exit 1
fi

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
install_root=/opt/guanghu/lake-lamp-authz

install -d -m 0755 "$install_root"
for file in server.js workorder-manager.js map-gate.js smtp-mailer.js action-client.js architecture-provision-broker.js deployment-event.js deployment-event-worker.js deployment-source-policy.js; do
  install -m 0644 "$script_dir/$file" "$install_root/$file"
done
install -m 0644 "$script_dir/lake-lamp-architecture-provision.service" /etc/systemd/system/lake-lamp-architecture-provision.service
install -m 0644 "$script_dir/lake-lamp-deployment-event-worker.service" /etc/systemd/system/lake-lamp-deployment-event-worker.service
install -d -m 0700 /var/lib/guanghu/architecture-provision
install -d -m 0750 /var/lib/guanghu/deployment-events
install -d -m 0700 /var/lib/guanghu/deployment-events/receipts
install -d -m 0755 /opt/guanghu/architecture-releases
install -d -m 0755 /etc/guanghu/lake-lamp
if [[ ! -e /etc/guanghu/lake-lamp/deployment-repositories.json ]]; then
  install -m 0644 "$script_dir/deployment-repositories.example.json" /etc/guanghu/lake-lamp/deployment-repositories.json
fi

systemctl daemon-reload
systemctl enable --now lake-lamp-architecture-provision.service
systemctl restart lake-lamp-authz.service
systemctl enable --now lake-lamp-deployment-event-worker.service
systemctl is-active --quiet lake-lamp-architecture-provision.service
systemctl is-active --quiet lake-lamp-authz.service
systemctl is-active --quiet lake-lamp-deployment-event-worker.service
echo ARCHITECTURE_PROVISIONER_INSTALLED
