#!/bin/sh
set -eu
case "$1" in
  install|upgrade)
    . /etc/os-release
    if [ "${ID:-}" != ubuntu ] || [ "${VERSION_ID:-}" != 24.04 ]; then
      echo "K1 integration requires Ubuntu 24.04 amd64." >&2
      exit 1
    fi
    if [ -d /run/systemd/system ]; then
      if [ -S /run/mission-core-k1/driver.sock ]; then
        if ! /usr/bin/python3 -I -c 'import http.client,json,socket; c=http.client.HTTPConnection("k1",timeout=5); c.sock=socket.socket(socket.AF_UNIX); c.sock.settimeout(5); c.sock.connect("/run/mission-core-k1/driver.sock"); c.request("GET","/prepare-safe"); r=c.getresponse(); assert r.status==200 and json.load(r).get("safe") is True'; then
          echo "Завершите подключение или запись K1 перед обновлением интеграции." >&2
          exit 1
        fi
      fi
      if [ -f /usr/lib/systemd/system/mission-core-k1.service ]; then
        systemctl stop mission-core-k1.service
      fi
    fi
    ;;
esac
