#!/bin/sh
# Runtime model sync for Unishift Ollama.
# Ensures models from manifest/env exist, then runs ollama (usually "serve").
set -eu

MODEL_BASE_URL="${OLLAMA_MODEL_BASE_URL:-https://storage.unishift.ru/models}"
DEFAULT_MANIFEST="${OLLAMA_MODELS_MANIFEST:-}"
FORCE="${OLLAMA_FORCE_UPDATE:-false}"
TMP_DIR="${OLLAMA_SYNC_TMP:-/tmp/ollama-sync}"
READY_TIMEOUT="${OLLAMA_READY_TIMEOUT:-120}"
SKIP_SYNC="${OLLAMA_SKIP_SYNC:-false}"

log() { echo "[ollama-sync] $*"; }

model_present() {
  name="$1"
  ollama show "$name" >/dev/null 2>&1
}

wait_ready() {
  i=0
  while [ "$i" -lt "$READY_TIMEOUT" ]; do
    if ollama list >/dev/null 2>&1; then
      return 0
    fi
    i=$((i + 1))
    sleep 1
  done
  log "ERROR: ollama did not become ready in ${READY_TIMEOUT}s"
  return 1
}

install_pull() {
  name="$1"
  if model_present "$name" && [ "$FORCE" != "true" ] && [ "$FORCE" != "1" ]; then
    log "skip (present): $name"
    return 0
  fi
  if model_present "$name" && { [ "$FORCE" = "true" ] || [ "$FORCE" = "1" ]; }; then
    log "force remove: $name"
    ollama rm "$name" || true
  fi
  log "pull: $name"
  ollama pull "$name"
}

install_gguf() {
  name="$1"
  source="$2"
  if model_present "$name" && [ "$FORCE" != "true" ] && [ "$FORCE" != "1" ]; then
    log "skip (present): $name"
    return 0
  fi
  if model_present "$name" && { [ "$FORCE" = "true" ] || [ "$FORCE" = "1" ]; }; then
    log "force remove: $name"
    ollama rm "$name" || true
  fi

  case "$source" in
    http://*|https://*) url="$source" ;;
    *) url="${MODEL_BASE_URL%/}/$source" ;;
  esac

  mkdir -p "$TMP_DIR"
  gguf="$TMP_DIR/${name}.gguf"
  modelfile="$TMP_DIR/Modelfile.${name}"

  log "download: $name <- $url"
  curl -fSL --retry 3 --retry-delay 2 -o "$gguf" "$url"
  printf 'FROM %s\n' "$gguf" >"$modelfile"
  log "create: $name"
  ollama create "$name" -f "$modelfile"
  rm -f "$gguf" "$modelfile"
}

default_source_for() {
  name="$1"
  case "$name" in
    qwen-*|littlelamb-*) echo "${name}.gguf" ;;
    *) echo "pull" ;;
  esac
}

sync_line() {
  line="$1"
  case "$line" in
    ''|\#*) return 0 ;;
  esac
  name=$(printf '%s' "$line" | awk '{print $1}')
  source=$(printf '%s' "$line" | awk '{print $2}')
  [ -n "$name" ] || return 0
  if [ -z "$source" ]; then
    source=$(default_source_for "$name")
  fi

  case "$source" in
    pull) install_pull "$name" ;;
    *) install_gguf "$name" "$source" ;;
  esac
}

load_manifest_file() {
  file="$1"
  [ -f "$file" ] || {
    log "ERROR: manifest not found: $file"
    return 1
  }
  log "manifest file: $file"
  while IFS= read -r line || [ -n "$line" ]; do
    sync_line "$line"
  done <"$file"
}

sync_from_env_list() {
  list="$1"
  log "manifest from OLLAMA_MODELS"
  old_ifs=$IFS
  IFS=,
  # shellcheck disable=SC2086
  set -- $list
  IFS=$old_ifs
  for item in "$@"; do
    item=$(printf '%s' "$item" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
    [ -n "$item" ] || continue
    case "$item" in
      *=*)
        name=${item%%=*}
        source=${item#*=}
        sync_line "$name $source"
        ;;
      *)
        sync_line "$item"
        ;;
    esac
  done
}

sync_models() {
  if [ -n "${OLLAMA_MODELS:-}" ]; then
    sync_from_env_list "$OLLAMA_MODELS"
    return
  fi

  if [ -n "${OLLAMA_MODELS_MANIFEST_URL:-}" ]; then
    mkdir -p "$TMP_DIR"
    remote="$TMP_DIR/models.manifest.remote"
    log "fetch manifest: $OLLAMA_MODELS_MANIFEST_URL"
    curl -fSL --retry 3 --retry-delay 2 -o "$remote" "$OLLAMA_MODELS_MANIFEST_URL"
    load_manifest_file "$remote"
    rm -f "$remote"
    return
  fi

  if [ -n "$DEFAULT_MANIFEST" ]; then
    load_manifest_file "$DEFAULT_MANIFEST"
    return
  fi

  log "no model list — skip sync"
}

run_sync_against_live_server() {
  if [ "$SKIP_SYNC" = "true" ] || [ "$SKIP_SYNC" = "1" ]; then
    log "OLLAMA_SKIP_SYNC set — skipping model sync"
    return 0
  fi
  wait_ready
  log "syncing models"
  sync_models
  log "sync complete"
}

# --- main ---
# Non-serve commands (pull/list/run) pass through without sync.
if [ "${1:-}" != "serve" ] && [ $# -gt 0 ]; then
  exec /bin/ollama "$@"
fi

log "starting ollama serve"
/bin/ollama serve &
OLLAMA_PID=$!

shutdown() {
  log "shutting down (pid $OLLAMA_PID)"
  kill "$OLLAMA_PID" 2>/dev/null || true
  wait "$OLLAMA_PID" 2>/dev/null || true
}
trap shutdown TERM INT

# Sync may fail on network; still keep serve up so compose can inspect logs.
if ! run_sync_against_live_server; then
  log "WARNING: model sync failed — ollama stays up with whatever is already installed"
fi

wait "$OLLAMA_PID"
