#!/bin/sh
# HIOB MCP 0.5.0 — no sudo, no credentials, no paid generation.
set -eu
umask 077
fail() { printf '%s\n' "$1" >&2; exit 1; }
mode=generic
case "${1:-}" in
  --check) mode=check ;;
  --codex) mode=codex ;;
  '') ;;
  *) fail '사용법: sh hiob-install.sh [--check | --codex]' ;;
esac
[ "$#" -le 1 ] || fail '한 가지 설치 모드만 지정하세요.'
[ "$(uname -s)" = Darwin ] || fail '현재 설치 프로그램과 최종 렌더는 macOS용입니다. Windows 렌더는 미지원입니다.'
case "$(uname -m)" in arm64) ;; x86_64) printf '%s\n' '주의: 0.5.0 Intel Mac 실측 검증은 아직 완료하지 않았습니다.' ;; *) fail '지원하지 않는 Mac 아키텍처입니다.' ;; esac
for tool in node npm curl shasum ffmpeg ffprobe otool; do
  command -v "$tool" >/dev/null 2>&1 || fail "필수 프로그램을 먼저 설치하세요: $tool (https://studio.hi-ob.com/mcp/install)"
done
if [ "$mode" = codex ]; then
  command -v codex >/dev/null 2>&1 || fail 'Codex CLI가 없습니다. 일반 MCP 설치는 --codex 없이 실행하세요.'
fi
node -e 'const [a,b]=process.versions.node.split(".").map(Number);process.exit(a>22||(a===22&&b>=18)?0:1)' || fail 'Node.js 22.18 이상이 필요합니다.'
if [ "$mode" = check ]; then
  printf '%s\n' '기본 의존성 확인 통과. 설치 후 doctor, AI 앱 안에서는 runtime_check로 실행 권한을 확인하세요.'
  exit 0
fi
release='0.5.0'
sha='d372cb63c1157408b489d27017fda6b1e17842ac4481219b02c02cbfceb61035'
root="${HIOB_INSTALL_DIR:-$HOME/.local/share/hiob-mcp}"
case "$root" in /*) ;; *) fail 'HIOB_INSTALL_DIR은 절대 경로여야 합니다.' ;; esac
destination="$root/releases/$release"
workspace="$HOME/Documents/HIOB Sources"
node_bin=$(command -v node)
cli="$destination/node_modules/@hiob/mcp/src/cli.mjs"
tool_path="$(dirname "$node_bin"):$(dirname "$(command -v ffmpeg)"):$(dirname "$(command -v ffprobe)"):/usr/bin:/bin:/usr/sbin:/sbin"
mkdir -p "$root/releases"
staging=$(mktemp -d "$root/releases/.install.XXXXXXXX")
trap 'rm -rf "$staging"' EXIT HUP INT TERM

# Registration is opt-in; never replace an unknown or older registration.
if [ "$mode" = codex ] && codex mcp get hiob --json >"$staging/registration.json" 2>/dev/null; then
  node -e 'const fs=require("fs"),c=JSON.parse(fs.readFileSync(process.argv[1],"utf8")),t=c.transport||c;process.exit(t.command===process.argv[2]&&JSON.stringify(t.args)===JSON.stringify([process.argv[3],"serve","--workspace",process.argv[4]])&&JSON.stringify(t.env||{})===JSON.stringify({PATH:process.argv[5]})?0:1)' "$staging/registration.json" "$node_bin" "$cli" "$workspace" "$tool_path" || fail '기존 hiob 등록을 보존했습니다. codex mcp get hiob로 확인하고, 교체하려면 codex mcp remove hiob 후 --codex로 다시 설치하세요. 프로젝트와 연결 파일은 삭제하지 않습니다.'
fi
if [ ! -f "$destination/.release-sha256" ] || [ "$(cat "$destination/.release-sha256")" != "$sha" ] || [ ! -f "$cli" ]; then
  [ ! -e "$destination" ] || fail '불완전하거나 다른 설치가 있습니다. 기존 폴더를 별도 보관한 후 다시 설치하세요.'
  curl --fail --show-error --location --proto '=https' --tlsv1.2 'https://studio.hi-ob.com/downloads/mcp/hiob-mcp-0.5.0.tgz' -o "$staging/package.tgz"
  actual=$(shasum -a 256 "$staging/package.tgz" | cut -d ' ' -f 1)
  [ "$actual" = "$sha" ] || fail '패키지 무결성 검사 실패: 설치를 중단했습니다.'
  npm install --prefix "$staging/app" --omit=dev --ignore-scripts --no-audit --no-fund "$staging/package.tgz"
  printf '%s\n' "$sha" > "$staging/app/.release-sha256"
  mv "$staging/app" "$destination"
fi
"$node_bin" "$cli" setup-renderer
"$node_bin" "$cli" doctor || fail '이 실행 환경에서 렌더 준비가 안 됐습니다. sandbox_execution 실패는 실행한 AI 앱의 권한 설정을 확인하세요.'
mkdir -p "$workspace"
config="$root/mcp-$release.json"
"$node_bin" -e 'const fs=require("fs");fs.writeFileSync(process.argv[1],JSON.stringify({mcpServers:{hiob:{command:process.argv[2],args:[process.argv[3],"serve","--workspace",process.argv[4]],env:{PATH:process.argv[5]}}}},null,2)+"\n",{mode:0o600})' "$staging/config.json" "$node_bin" "$cli" "$workspace" "$tool_path"
mv "$staging/config.json" "$config"
if [ "$mode" = codex ]; then
  codex mcp add hiob --env "PATH=$tool_path" -- "$node_bin" "$cli" serve --workspace "$workspace"
  printf '%s\n' 'Codex 등록을 마쳤습니다. Codex를 다시 열어주세요.'
else
  printf '%s\n' '설치 완료. AI 앱의 MCP 설정에 아래 JSON을 추가한 뒤 연결하세요.'
  cat "$config"
fi
printf '%s\n' "설정 파일: $config" '계정·프로젝트 연결: https://studio.hi-ob.com/mcp' '앱 안에서 runtime_check를 먼저 실행하세요. 터미널 점검과 앱의 실행 권한은 다를 수 있습니다.'
