File size: 22,393 Bytes
0e2b571
 
65f8d7e
0e2b571
 
 
 
 
 
 
 
 
65f8d7e
 
 
 
 
 
 
 
 
 
 
0e2b571
 
 
 
65f8d7e
 
 
 
0e2b571
 
 
 
 
 
 
 
 
 
65f8d7e
 
0e2b571
65f8d7e
0e2b571
 
65f8d7e
0e2b571
 
 
 
 
 
65f8d7e
 
 
0e2b571
 
 
 
 
 
 
65f8d7e
0e2b571
65f8d7e
0e2b571
 
 
65f8d7e
 
 
 
 
 
 
 
 
 
 
 
0e2b571
 
 
65f8d7e
 
 
 
 
0e2b571
65f8d7e
0e2b571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65f8d7e
0e2b571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65f8d7e
0e2b571
 
 
 
65f8d7e
0e2b571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65f8d7e
0e2b571
 
 
65f8d7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e2b571
65f8d7e
0e2b571
 
 
65f8d7e
 
0e2b571
65f8d7e
 
 
 
 
 
 
 
0e2b571
 
65f8d7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e2b571
 
 
65f8d7e
0e2b571
 
 
65f8d7e
0e2b571
 
 
 
 
 
 
 
 
 
 
 
 
65f8d7e
 
 
 
 
0e2b571
65f8d7e
 
 
 
 
 
 
 
 
 
0e2b571
 
65f8d7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e2b571
 
 
65f8d7e
 
0e2b571
 
 
65f8d7e
 
 
 
 
 
 
 
 
 
 
 
0e2b571
 
 
 
65f8d7e
 
 
 
0e2b571
65f8d7e
 
 
0e2b571
65f8d7e
 
 
0e2b571
 
65f8d7e
0e2b571
65f8d7e
 
 
0e2b571
 
 
 
 
 
 
 
 
 
 
 
65f8d7e
 
 
 
 
 
 
0e2b571
 
 
 
 
65f8d7e
0e2b571
 
 
 
 
 
65f8d7e
 
0e2b571
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
#!/usr/bin/env bash
#
# Local DE Coach β€” one-line cross-platform installer (v1.1.0)
#
#   curl -fsSL https://istias.tech/install.sh | bash
#   curl -fsSL https://istias.tech/install.sh | bash -s -- --model vosk-small
#
# What it does, end to end:
#   1. Detects your OS + package manager (Arch pacman / Debian-Ubuntu apt /
#      Fedora dnf / macOS brew / Windows β†’ WSL2 guidance).
#   2. Installs the system dependencies (python3, ffmpeg, node, npm, git...).
#   3. Downloads the project ZIP β€” NO GitHub login needed (HuggingFace mirror,
#      same URL every time β€” always the newest version).
#   4. If an install already exists β†’ you pick:
#        [1] UPDATE it  (keeps venv, models, your model choice β€” code only)
#        [2] CHANGE the ASR model only (no download if already on disk)
#        [3] FRESH install (wipe + reinstall)
#   5. Runs ./setup.sh β€” the interactive model menu appears, models already
#      on disk are marked, you can also pick "use an already-downloaded
#      model". Setup continues by itself until fully finished.
#   6. Prints your START / STOP commands β€” you only have to remember two.
#
# Re-running the SAME one-liner later = update to the newest version.
#
# Flags:
#   --model <name>     skip the menu: distil | turbo-de | vosk-de | vosk-small | large-de
#   -y, --yes          non-interactive (no questions, defaults everywhere)
#   --dir <path>       install location (default: ./local-de-coach, or the last install)
#   --update           force UPDATE mode on an existing install
#   --change-model     only switch the ASR model on an existing install (fast)
#   --fresh            wipe + reinstall (no venv / model preservation)
#   --no-sysdeps       don't touch system packages (deps already installed)
#   --dry-run          show the plan, change nothing
#   --zip-url <url>    override download URL (advanced)
#   --help
#
set -euo pipefail

# ─── Colors (TTY-aware) ─────────────────────────────────────────────────────
if [[ -t 1 ]]; then
  RED=$'\033[0;31m';   GREEN=$'\033[0;32m';  YELLOW=$'\033[0;33m'
  BLUE=$'\033[0;34m';  CYAN=$'\033[0;36m';   BOLD=$'\033[1m'
  DIM=$'\033[2m';      NC=$'\033[0m'
else
  RED=''; GREEN=''; YELLOW=''; BLUE=''; CYAN=''; BOLD=''; DIM=''; NC=''
fi
RULE="────────────────────────────────────────────────────────────"
hr()  { printf "  ${DIM}%s${NC}\n" "$RULE"; }
log() { printf "  ${BLUE}Β·${NC} %s\n" "$*"; }
ok()  { printf "  ${GREEN}βœ“${NC} %s\n" "$*"; }
warn(){ printf "  ${YELLOW}!${NC} %s\n" "$*"; }
err() { printf "  ${RED}βœ—${NC} %s\n" "$*" >&2; exit 1; }
info(){ printf "  ${CYAN}β†’${NC} %s\n" "$*"; }

ZIP_PRIMARY="https://huggingface.co/Local-DE-Coach/app/resolve/main/Local-DE-Coach-latest.zip"
ZIP_FALLBACK="https://huggingface.co/Local-DE-Coach/app/resolve/main/Local-DE-Coach-2.1.4.zip"
POINTER="$HOME/.cache/local-de-coach/last-install"

MODEL_ARG=""
ASSUME_YES=false
NO_SYSDEPS=false
DRY_RUN=false
DEST_DIR=""
ZIP_URL="$ZIP_PRIMARY"
ACTION=""   # "" | update | model | fresh

usage() { sed -n '2,33p' "$0" | sed 's/^# \{0,1\}//'; exit 0; }

while [[ $# -gt 0 ]]; do
  case "$1" in
    --model)       [[ $# -lt 2 ]] && err "--model needs a value"; MODEL_ARG="$2"; shift 2 ;;
    --model=*)     MODEL_ARG="${1#--model=}"; shift ;;
    -y|--yes)      ASSUME_YES=true; shift ;;
    --no-sysdeps)  NO_SYSDEPS=true; shift ;;
    --dry-run)     DRY_RUN=true; shift ;;
    --dir)         [[ $# -lt 2 ]] && err "--dir needs a path"; DEST_DIR="$2"; shift 2 ;;
    --zip-url)     [[ $# -lt 2 ]] && err "--zip-url needs a URL"; ZIP_URL="$2"; shift 2 ;;
    --update)      ACTION="update"; shift ;;
    --change-model|--model-only) ACTION="model"; shift ;;
    --fresh)       ACTION="fresh"; shift ;;
    -h|--help)     usage ;;
    *)             err "unknown option: $1  (try --help)" ;;
  esac
done

case "$MODEL_ARG" in
  ""|distil|turbo-de|vosk-de|vosk-small|large-de) : ;;
  *) err "unknown model '$MODEL_ARG' β€” pick: distil | turbo-de | vosk-de | vosk-small | large-de" ;;
esac

# ─── Banner ─────────────────────────────────────────────────────────────────
printf "\n${BOLD}  Local DE Coach β€” installer v1.1.0${NC}\n"
hr

# ─── 1. Detect OS + package manager ─────────────────────────────────────────
OS_NAME="$(uname -s)"
ARCH="$(uname -m)"
PKG_MGR=""; OS_LABEL=""

case "$OS_NAME" in
  Linux)  OS_LABEL="Linux (${ARCH})"
          if   command -v apt-get  >/dev/null 2>&1; then PKG_MGR="apt"
          elif command -v pacman   >/dev/null 2>&1; then PKG_MGR="pacman"
          elif command -v dnf      >/dev/null 2>&1; then PKG_MGR="dnf"
          elif command -v yum      >/dev/null 2>&1; then PKG_MGR="dnf"
          elif command -v zypper   >/dev/null 2>&1; then PKG_MGR="zypper"
          fi
          if grep -qi microsoft /proc/version 2>/dev/null; then OS_LABEL="${OS_LABEL} β€” WSL2"; fi ;;
  Darwin) OS_LABEL="macOS (${ARCH})"; PKG_MGR="brew" ;;
  MINGW*|MSYS*|CYGWIN*)
          printf "\n${RED}βœ— Windows shell detected (Git Bash / MSYS).${NC}\n"
          printf "\n  ${BOLD}Local DE Coach on Windows β†’ use WSL2 (takes 3 minutes):${NC}\n\n"
          printf "  1. Open PowerShell ${BOLD}as Administrator${NC} and run:\n"
          printf "       wsl --install -d Ubuntu\n"
          printf "  2. Reboot when asked, open the ${BOLD}Ubuntu${NC} app, create a user.\n"
          printf "  3. Inside Ubuntu run the SAME one-line command:\n"
          printf "       ${CYAN}curl -fsSL https://istias.tech/install.sh | bash${NC}\n\n"
          exit 1 ;;
  *) err "unsupported OS: $OS_NAME (use Linux, macOS, or Windows via WSL2)" ;;
esac

log "Detected: ${BOLD}${OS_LABEL}${NC}  Β·  package manager: ${BOLD}${PKG_MGR:-none}${NC}"
if [[ -z "$PKG_MGR" ]]; then
  warn "No known package manager found β€” continuing WITHOUT system-dep install."
  warn "Make sure you already have: python3 + pip + venv, ffmpeg, node β‰₯18, npm, git."
  NO_SYSDEPS=true
fi

# ─── 2. System dependencies ─────────────────────────────────────────────────
SUDO=""
if [[ $EUID -ne 0 ]] && command -v sudo >/dev/null 2>&1; then SUDO="sudo"; fi

missing_cmds() {
  local miss=()
  for c in "$@"; do command -v "$c" >/dev/null 2>&1 || miss+=("$c"); done
  [[ ${#miss[@]} -eq 0 ]] && return 0 || printf '%s\n' "${miss[@]}"
}

node_ok() { command -v node >/dev/null 2>&1 && [[ "$(node -v | sed 's/v\([0-9]*\).*/\1/')" -ge 18 ]]; }

install_sysdeps() {
  case "$PKG_MGR" in
    pacman)
      $SUDO pacman -Sy --needed --noconfirm curl python python-pip ffmpeg libsndfile base-devel nodejs npm git unzip ;;
    apt)
      $SUDO apt-get update -qq
      $SUDO DEBIAN_FRONTEND=noninteractive apt-get install -y -qq \
        curl ca-certificates python3 python3-venv python3-pip ffmpeg \
        libsndfile1 build-essential git unzip
      if ! node_ok; then
        warn "node β‰₯18 not found β€” installing NodeSource 20.x"
        curl -fsSL https://deb.nodesource.com/setup_20.x | $SUDO -E bash -
        $SUDO DEBIAN_FRONTEND=noninteractive apt-get install -y -qq nodejs
      fi ;;
    dnf)
      $SUDO dnf install -y curl python3 python3-pip ffmpeg nodejs npm \
        gcc-c++ make git libsndfile unzip 2>/dev/null \
        || $SUDO dnf install -y curl python3 python3-pip nodejs npm gcc-c++ make git unzip
      node_ok || { warn "node β‰₯18 missing β€” see https://nodejs.org (dnf repo too old)"; return 1; } ;;
    zypper)
      $SUDO zypper install -y curl python3 python3-pip python3-venv ffmpeg nodejs npm \
        gcc-c++ make git libsndfile1 unzip ;;
    brew)
      command -v brew >/dev/null 2>&1 || {
        warn "Homebrew missing β€” install it first:"
        warn '  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"'
        return 1; }
      brew install curl python ffmpeg node git unzip ;;
  esac
}

if [[ "$ACTION" != "model" ]]; then
  if $NO_SYSDEPS; then
    ok "System deps: skipped (--no-sysdeps)"
  else
    info "Step 1/4 Β· system dependencies"
    $DRY_RUN && { log "(dry-run) would run: install_sysdeps via $PKG_MGR"; } || {
      install_sysdeps || err "system dependency install failed β€” fix the error above or re-run with --no-sysdeps"
    }
    if ! $DRY_RUN; then
      MISSING="$(missing_cmds python3 pip3 ffmpeg git || true)"
      if [[ -n "$MISSING" ]]; then
        warn "still missing after install: $MISSING"
        $ASSUME_YES || { printf "  continue anyway? [y/N] "; read -r ANSWER < /dev/tty || ANSWER=n
                         [[ "$ANSWER" == y || "$ANSWER" == Y ]] || err "aborted β€” install the tools above and re-run"; }
      fi
    fi
    ok "System deps ready"
  fi
fi

# ─── 3. Where is the project? (new / existing install) ──────────────────────
# Resolve install dir: --dir flag  >  ./local-de-coach  >  last install
if [[ -z "$DEST_DIR" ]]; then
  if   [[ -d "${LOCAL_DE_COACH_DIR:-$PWD/local-de-coach}/app" ]]; then
    DEST_DIR="${LOCAL_DE_COACH_DIR:-$PWD/local-de-coach}"
  elif [[ -f "$POINTER" ]] && [[ -d "$(cat "$POINTER" 2>/dev/null)/app" ]]; then
    DEST_DIR="$(cat "$POINTER")"
    log "found your existing install: $DEST_DIR"
  else
    DEST_DIR="${LOCAL_DE_COACH_DIR:-$PWD/local-de-coach}"
  fi
fi
DEST_DIR="$(mkdir -p "$DEST_DIR" && cd "$DEST_DIR" && pwd)"
APP_DIR="$DEST_DIR/app"

EXISTING=false
APP_VERSION=""; APP_MODEL=""
if [[ -f "$APP_DIR/setup.sh" ]]; then
  EXISTING=true
  APP_VERSION="$(sed -n 's/.*setup script (v\([0-9.]*\)).*/\1/p' "$APP_DIR/setup.sh" | head -1)"
  if [[ -f "$APP_DIR/backend/setup_state.json" ]]; then
    APP_MODEL="$(sed -n 's/.*"default_score_model": *"\([^"]*\)".*/\1/p' "$APP_DIR/backend/setup_state.json" | head -1)"
    [[ "$APP_MODEL" == "vosk" ]] && APP_MODEL="vosk-small"
  fi
fi

# ─── Choose the action when an install already exists ──────────────────────
if [[ "$ACTION" == "model" && "$EXISTING" != "true" ]]; then
  err "no existing install at $APP_DIR β€” run the installer normally first"
fi

if [[ -z "$ACTION" ]]; then
  if [[ "$EXISTING" == "true" ]]; then
    if $ASSUME_YES; then
      ACTION="update"
    else
      echo ""
      printf "  ${BOLD}Existing install found${NC}  ${DIM}${APP_DIR}  (v${APP_VERSION:-?}${APP_MODEL:+  Β·  model: ${APP_MODEL}})${NC}\n"
      hr
      printf "    ${BOLD}1${NC})  ${BOLD}Update${NC} to the newest version   ${DIM}(keeps venv, models, settings)${NC}\n"
      printf "    ${BOLD}2${NC})  ${BOLD}Change the ASR model only${NC}      ${DIM}(already-downloaded models = no download)${NC}\n"
      printf "    ${BOLD}3${NC})  ${BOLD}Fresh install${NC}                  ${DIM}(wipe + reinstall everything)${NC}\n"
      echo ""
      printf "  ${CYAN}Choice [1-3, Enter=1]:${NC} "
      if [[ -t 0 ]]; then read -r CHOICE || CHOICE="1"; else CHOICE="1"; fi
      case "${CHOICE:-1}" in
        1) ACTION="update" ;;
        2) ACTION="model" ;;
        3) ACTION="fresh" ;;
        *) err "invalid choice '${CHOICE}'" ;;
      esac
    fi
  else
    ACTION="install"
  fi
fi

# ─── 4a. CHANGE-MODEL-ONLY fast path ────────────────────────────────────────
if [[ "$ACTION" == "model" ]]; then
  info "Step 2/4 Β· change the ASR model (fast path β€” no code changes)"
  SETUP_ARGS=(--change-model)
  [[ -n "$MODEL_ARG" ]] && SETUP_ARGS+=(--model "$MODEL_ARG")
  if $DRY_RUN; then
    log "(dry-run) would run: setup.sh ${SETUP_ARGS[*]}"
  else
    chmod +x "$APP_DIR/setup.sh" 2>/dev/null || true
    if ! $ASSUME_YES && [[ -t 0 || -e /dev/tty ]]; then
      bash "$APP_DIR/setup.sh" "${SETUP_ARGS[@]}" < /dev/tty
    else
      [[ -n "$MODEL_ARG" ]] || err "--yes needs --model <name> for --change-model"
      bash "$APP_DIR/setup.sh" "${SETUP_ARGS[@]}"
    fi
  fi
  # ── finish (same cheat-sheet as the main path)
  info "Step 3/4 Β· writing your command cheat-sheet"
  write_cheatsheet_and_finish() {
    CHEAT="$DEST_DIR/COMMANDS.txt"
    cat > "$CHEAT" <<EOF
Local DE Coach β€” your commands
==============================

cd $APP_DIR

  ./DE-Coach --start     START the app  β†’ open http://127.0.0.1:33111
  ./DE-Coach --server    START for LAN/VPS (reachable from other devices)
  ./DE-Coach --stop      STOP everything
  ./DE-Coach --dev       dev mode (live logs in this terminal)

  Change ASR model:        ./setup.sh --change-model
                           (menu: download a new one OR use an
                            already-downloaded model β€” no re-download)
  Switch model directly:   ./setup.sh --model vosk-small   (fits 500 MB RAM)
  Update to newest:        curl -fsSL https://istias.tech/install.sh | bash

  Logs: ./logs/
EOF
    ok "cheat-sheet saved β†’ $CHEAT"
    printf "\n"
    printf "  ${GREEN}${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n"
    printf "  ${GREEN}${BOLD}  Done β€” model switched!${NC}\n"
    printf "  ${GREEN}${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n\n"
    printf "  ${BOLD}Your commands${NC} (also saved in COMMANDS.txt):\n\n"
    printf "    ${CYAN}cd $APP_DIR${NC}\n\n"
    printf "    ${GREEN}./DE-Coach --start${NC}      ${DIM}# START β†’ http://127.0.0.1:33111${NC}\n"
    printf "    ${GREEN}./DE-Coach --stop${NC}       ${DIM}# STOP everything${NC}\n\n"
    printf "  ${DIM}Update later (same URL): curl -fsSL https://istias.tech/install.sh | bash${NC}\n"
    printf "\n"
  }
  write_cheatsheet_and_finish
  exit 0
fi

# ─── 4b. Download + extract (UPDATE or INSTALL/FRESH) ──────────────────────
if [[ "$ACTION" == "update" ]]; then
  info "Step 2/4 Β· download the update (same URL, newest version)"
else
  info "Step 2/4 Β· download the project (no login needed)"
fi

if pgrep -f "uvicorn.*server:app" >/dev/null 2>&1 || pgrep -f "DE-Coach" >/dev/null 2>&1; then
  warn "the app seems to be RUNNING right now β€” updating files is safe,"
  warn "but restart it afterwards:  ./DE-Coach --stop && ./DE-Coach --start"
fi

if $DRY_RUN; then
  log "(dry-run) would download: $ZIP_URL"
  log "(dry-run) would extract into: $DEST_DIR (action: $ACTION)"
else
  dl() { curl -fL --retry 3 --retry-delay 2 --connect-timeout 20 -o "$1" "$2"; }
  TMP_ZIP="$DEST_DIR/.download.zip"
  log "downloading latest version ..."
  if ! dl "$TMP_ZIP" "$ZIP_URL"; then
    warn "primary mirror failed β€” trying fallback"
    dl "$TMP_ZIP" "$ZIP_FALLBACK" || err "download failed β€” check your internet and re-run"
  fi
  # verify it is a real zip (> 500 KB) using python3 (unzip is not always installed)
  python3 - "$TMP_ZIP" <<'PY' || err "downloaded file is not a valid ZIP β€” re-run"
import sys, zipfile, os
p = sys.argv[1]
assert os.path.getsize(p) > 500_000, "zip too small"
with zipfile.ZipFile(p) as z:
    assert z.testzip() is None, "zip corrupt"
print("zip OK:", len(z.namelist()), "files")
PY
  # extract into a staging dir, then swap β€” preserves venv + node_modules
  STAGE="$DEST_DIR/.app.new"
  rm -rf "$STAGE"
  mkdir -p "$STAGE"
  python3 -c "import zipfile,sys; zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])" "$TMP_ZIP" "$STAGE"
  rm -f "$TMP_ZIP"
  # handle zips that ship a single top-level folder
  if [[ ! -f "$STAGE/setup.sh" ]]; then
    sub="$(find "$STAGE" -mindepth 1 -maxdepth 1 -type d | head -1)"
    if [[ -n "$sub" && -f "$sub/setup.sh" ]]; then
      mv "$sub" "$STAGE/.inner" && rm -rf "$STAGE" && mv "$STAGE/.inner" "$STAGE"
    fi
  fi
  [[ -f "$STAGE/setup.sh" ]] || err "extracted zip has no setup.sh β€” unexpected layout"
  NEW_VERSION="$(sed -n 's/.*setup script (v\([0-9.]*\)).*/\1/p' "$STAGE/setup.sh" | head -1)"
  ok "downloaded version: v${NEW_VERSION:-?}"
fi

# ─── 4c. Swap the code (preserving venv / node_modules / setup_state) ──────
if $DRY_RUN; then
  log "(dry-run) would swap code into $APP_DIR (action: $ACTION)"
else
  if [[ "$EXISTING" == "true" && "$ACTION" == "update" ]]; then
    if [[ -n "$APP_VERSION" && "$APP_VERSION" == "$NEW_VERSION" ]]; then
      log "already at v$NEW_VERSION β€” refreshing files anyway (idempotent)"
    else
      log "updating: v${APP_VERSION:-?} β†’ v${NEW_VERSION:-?}"
    fi
    rm -rf "$DEST_DIR/app.bak"
    mv "$APP_DIR" "$DEST_DIR/app.bak"
    mv "$STAGE" "$APP_DIR"
    mkdir -p "$APP_DIR/backend" "$APP_DIR/frontend"
    # preserve: venv, node_modules, setup_state (remembers your model)
    if [[ -d "$DEST_DIR/app.bak/backend/.venv" ]]; then
      mv "$DEST_DIR/app.bak/backend/.venv" "$APP_DIR/backend/.venv" && ok "kept: Python venv (no re-download of pip packages)"
    fi
    if [[ -d "$DEST_DIR/app.bak/frontend/node_modules" ]]; then
      mv "$DEST_DIR/app.bak/frontend/node_modules" "$APP_DIR/frontend/node_modules" && ok "kept: node_modules (no re-download of npm packages)"
    fi
    if [[ -f "$DEST_DIR/app.bak/backend/setup_state.json" ]]; then
      cp "$DEST_DIR/app.bak/backend/setup_state.json" "$APP_DIR/backend/setup_state.json" \
        && ok "kept: your model choice (${APP_MODEL:-unknown})"
    fi
    warn "previous version backed up at $DEST_DIR/app.bak (removed after setup succeeds)"
  else
    # fresh install (or install over nothing)
    if [[ -d "$APP_DIR" ]]; then
      rm -rf "$DEST_DIR/app.bak"
      mv "$APP_DIR" "$DEST_DIR/app.bak"
      warn "old app/ moved aside to app.bak"
    fi
    mv "$STAGE" "$APP_DIR"
    ok "extracted β†’ $APP_DIR"
  fi
fi

# ─── 5. Model selection + setup (runs until fully finished) ────────────────
info "Step 3/4 Β· model selection + full setup"
if $DRY_RUN; then
  log "(dry-run) would run: ./setup.sh --no-sysdeps ${MODEL_ARG:+--model $MODEL_ARG}"
  log "  model menu marks already-downloaded models and has a"
  log "  'use an already-downloaded model' option (zero download)"
else
  chmod +x "$APP_DIR/setup.sh" "$APP_DIR/DE-Coach" 2>/dev/null || true
  SETUP_ARGS=(--no-sysdeps)
  if [[ -n "$MODEL_ARG" ]]; then
    SETUP_ARGS+=(--model "$MODEL_ARG")
  elif $ASSUME_YES && [[ -n "$APP_MODEL" ]]; then
    # non-interactive update: keep whatever model the user already had
    SETUP_ARGS+=(--model "$APP_MODEL")
    log "non-interactive update β€” keeping model: $APP_MODEL"
  elif $ASSUME_YES; then
    # non-interactive fresh install: default to the low-RAM-safe model
    SETUP_ARGS+=(--model vosk-small)
    log "non-interactive fresh install β€” defaulting to vosk-small (lowest RAM, ~400 MB)"
    log "  override with: curl -fsSL https://istias.tech/install.sh | bash -s -- --model <name>"
  fi

  # `curl | bash` consumes stdin with the script β€” reattach stdin to the
  # terminal so setup.sh's interactive model menu still works.
  if ! $ASSUME_YES && [[ -t 0 || -e /dev/tty ]]; then
    log "opening the model menu β€” pick what you want (Enter keeps your model):"
    bash "$APP_DIR/setup.sh" "${SETUP_ARGS[@]}" < /dev/tty \
      || { [[ -d "$DEST_DIR/app.bak" ]] && warn "setup failed β€” your previous install is safe at: $DEST_DIR/app.bak"
           err "setup failed β€” see the output above"; }
  else
    bash "$APP_DIR/setup.sh" "${SETUP_ARGS[@]}" \
      || { [[ -d "$DEST_DIR/app.bak" ]] && warn "setup failed β€” your previous install is safe at: $DEST_DIR/app.bak"
           err "setup failed β€” see the output above"; }
  fi

  # setup succeeded β†’ the backup can go
  [[ -d "$DEST_DIR/app.bak" ]] && rm -rf "$DEST_DIR/app.bak" && ok "old version cleaned up (app.bak removed)"
fi

# ─── 6. Finish β€” the only commands the user needs ──────────────────────────
info "Step 4/4 Β· writing your command cheat-sheet"
mkdir -p "$(dirname "$POINTER")" 2>/dev/null || true
printf '%s' "$DEST_DIR" > "$POINTER" 2>/dev/null || true

CHEAT="$DEST_DIR/COMMANDS.txt"
cat > "$CHEAT" <<EOF
Local DE Coach β€” your commands
==============================

cd $APP_DIR

  ./DE-Coach --start     START the app  β†’ open http://127.0.0.1:33111
  ./DE-Coach --server    START for LAN/VPS (reachable from other devices)
  ./DE-Coach --stop      STOP everything
  ./DE-Coach --dev       dev mode (live logs in this terminal)

  Change ASR model:        ./setup.sh --change-model
                           (menu: download a new one OR use an
                            already-downloaded model β€” no re-download)
  Switch model directly:   ./setup.sh --model vosk-small   (fits 500 MB RAM)
  Update to newest:        curl -fsSL https://istias.tech/install.sh | bash

  Logs: ./logs/
EOF
ok "cheat-sheet saved β†’ $CHEAT"

printf "\n"
printf "  ${GREEN}${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n"
printf "  ${GREEN}${BOLD}  Install complete!  (v${NEW_VERSION:-?})${NC}\n"
printf "  ${GREEN}${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n\n"
printf "  ${BOLD}Your commands${NC} (also saved in COMMANDS.txt):\n\n"
printf "    ${CYAN}cd $APP_DIR${NC}\n\n"
printf "    ${GREEN}./DE-Coach --start${NC}      ${DIM}# START β†’ http://127.0.0.1:33111${NC}\n"
printf "    ${GREEN}./DE-Coach --server${NC}     ${DIM}# START for LAN / VPS (0.0.0.0)${NC}\n"
printf "    ${GREEN}./DE-Coach --stop${NC}       ${DIM}# STOP everything${NC}\n\n"
printf "  ${DIM}Change model later:  ./setup.sh --change-model  (already-downloaded = no download)${NC}\n"
printf "  ${DIM}Update later (same URL): curl -fsSL https://istias.tech/install.sh | bash${NC}\n"
printf "\n"