import { shQuote } from "./platform-infra-ops-library";

export interface SystemdSocketPairUnit {
  name: string;
  path: string;
  content: string;
}

export interface SystemdSocketPairConvergeSpec {
  socket: SystemdSocketPairUnit;
  service: SystemdSocketPairUnit;
  postconditionScript: string;
}

export function renderSystemdSocketPairConvergeScript(spec: SystemdSocketPairConvergeSpec): string {
  const socketContent = Buffer.from(spec.socket.content).toString("base64");
  const serviceContent = Buffer.from(spec.service.content).toString("base64");
  return `set -eu\ntmp=$(mktemp -d)\ntrap 'rm -rf "$tmp"' EXIT\nprintf %s ${shQuote(socketContent)} | base64 -d >"$tmp/socket"\nprintf %s ${shQuote(serviceContent)} | base64 -d >"$tmp/service"\nsocket_changed=false\nservice_changed=false\nsocket_active=false\nservice_active=false\ncmp -s "$tmp/socket" ${shQuote(spec.socket.path)} || socket_changed=true\ncmp -s "$tmp/service" ${shQuote(spec.service.path)} || service_changed=true\nsystemctl is-active --quiet ${shQuote(spec.socket.name)} && socket_active=true\nsystemctl is-active --quiet ${shQuote(spec.service.name)} && service_active=true\nif [ "$socket_changed" = true ] || [ "$service_changed" = true ]; then\n  if [ "$service_active" = true ]; then\n    systemctl stop ${shQuote(spec.service.name)}\n    service_active=false\n  fi\n  install -m 0644 "$tmp/socket" ${shQuote(spec.socket.path)}\n  install -m 0644 "$tmp/service" ${shQuote(spec.service.path)}\n  systemctl daemon-reload\nfi\nsystemctl enable ${shQuote(spec.socket.name)}\nif [ "$socket_changed" = true ]; then\n  systemctl restart ${shQuote(spec.socket.name)}\nelif [ "$socket_active" != true ]; then\n  if [ "$service_active" = true ]; then\n    systemctl stop ${shQuote(spec.service.name)}\n  fi\n  systemctl start ${shQuote(spec.socket.name)}\nfi\nprintf '{"socketChanged":%s,"serviceChanged":%s}\\n' "$socket_changed" "$service_changed"\n${spec.postconditionScript.trim()}\n`;
}
