#!/bin/bash

THIS_PATH="$( cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
ACTION="$1"
shift
PACKAGE_LIST=("$@")

INSTALL_PATH="/usr/local/lib/ollama"
BINARY_PATH="/usr/local/bin/ollama"
MODEL_PATH="/opt/ai/ollama/models"
CACHE_DIR="/var/cache/zero-lliurex-ollama"

# Modelos instalables en "name:tag" o "name" (= name:latest).
# Cada uno se expone como paquete ollama-model-<name> (:latest omitido) en ollama.epi
MODELS=("phi4-mini:latest" "qwen2.5vl:3b")

model_name() {
	echo "${1%%:*}"
}

model_tag() {
	if [[ "$1" == *:* ]]; then
		echo "${1##*:}"
	else
		echo "latest"
	fi
}

model_pkg() {
	echo "ollama-model-${1%:latest}"
}

model_manifest() {
	echo "$MODEL_PATH/manifests/registry.ollama.ai/library/$(model_name "$1")/$(model_tag "$1")"
}

has_pkg() {
	[[ " ${PACKAGE_LIST[*]} " == *" $1 "* ]]
}

apply_model_perms() {
	[ -d "$MODEL_PATH" ] || return 0
	chmod 2777 "$MODEL_PATH"
	find "$MODEL_PATH" -type d -exec chmod 2777 {} +
	find "$MODEL_PATH" -type f -exec chmod 666 {} +
}

blob_path() {
	echo "$MODEL_PATH/blobs/${1/:/-}"
}

manifest_digests() {
	grep -oE 'sha256:[0-9a-f]{64}' "$1" | sort -u
}

gc_blobs() {
	[ -d "$MODEL_PATH/blobs" ] || return 0
	local ref d b
	ref=$(grep -rhoE 'sha256:[0-9a-f]{64}' "$MODEL_PATH/manifests" 2>/dev/null | sort -u)
	for b in "$MODEL_PATH/blobs"/sha256-*; do
		[ -e "$b" ] || continue
		d="sha256:${b##*sha256-}"
		grep -qxF "$d" <<< "$ref" || rm -f "$b"
	done
}

remove_model() {
	local mfile="$MODEL_PATH/manifests/registry.ollama.ai/library/$1/$2"
	[ -f "$mfile" ] || return 0
	local digests d
	digests=$(manifest_digests "$mfile")
	rm -f "$mfile"
	rmdir -p --ignore-fail-on-non-empty "$(dirname "$mfile")" 2>/dev/null || true
	for d in $digests; do
		if ! grep -rqsF "$d" "$MODEL_PATH/manifests" 2>/dev/null; then
			rm -f "$(blob_path "$d")"
		fi
	done
	gc_blobs
	apply_model_perms
}

case $ACTION in

	getStatus)
		status=0
		found=0
		if has_pkg ollama; then
			found=1
			if [ ! -f "${BINARY_PATH}" ]; then
				status=1
			fi
		fi
		for m in "${MODELS[@]}"; do
			if has_pkg "$(model_pkg "$m")"; then
				found=1
				if [ ! -e "$(model_manifest "$m")" ]; then
					status=1
				fi
			fi
		done
		if [ "$found" -eq 0 ]; then
			echo "Not found!"
		else
			echo "$status"
		fi
	;;

	download)
		mkdir -p "$CACHE_DIR" || exit 1
		if ! curl -fSSL https://ollama.com/install.sh -o "$CACHE_DIR/install.sh"; then
			exit 1
		fi
	;;

	installPackage)
		if has_pkg ollama; then
			mkdir -p /etc/systemd/system/ollama.service.d/ || exit 1
			mkdir -p "$MODEL_PATH/blobs" || exit 1
			apply_model_perms
			echo -e "[Service]\nEnvironment=\"OLLAMA_MODELS=${MODEL_PATH}\"" > /etc/systemd/system/ollama.service.d/override.conf
			if [ -f "$CACHE_DIR/install.sh" ]; then
				sh "$CACHE_DIR/install.sh"
			else
				curl -fSSL https://ollama.com/install.sh | sh
			fi
			if [ ! -d "${INSTALL_PATH}" ]; then
				exit 1
			fi
		fi
		need_models=0
		for m in "${MODELS[@]}"; do
			if has_pkg "$(model_pkg "$m")"; then
				need_models=1
			fi
		done
		if [ "$need_models" -eq 1 ]; then
			mkdir -p "$MODEL_PATH/blobs" || exit 1
			systemctl start ollama || true
			ready=0
			for _ in $(seq 1 10); do
				if "${BINARY_PATH}" list >/dev/null 2>&1; then
					ready=1
					break
				fi
				sleep 1
			done
			if [ "$ready" -ne 1 ]; then
				exit 1
			fi
			for m in "${MODELS[@]}"; do
				if has_pkg "$(model_pkg "$m")"; then
					if ! "${BINARY_PATH}" pull "$m"; then
						exit 1
					fi
				fi
			done
			apply_model_perms
			systemctl restart ollama || true
		fi
	;;

	remove)
		for m in "${MODELS[@]}"; do
			if has_pkg "$(model_pkg "$m")"; then
				echo "Removing ollama model $m..."
				remove_model "$(model_name "$m")" "$(model_tag "$m")"
			fi
		done
		if has_pkg ollama; then
			echo "Removing ollama service..."
			systemctl stop ollama || true
			systemctl disable ollama || true
			rm -f /etc/systemd/system/ollama.service
			rm -rf /etc/systemd/system/ollama.service.d
			systemctl daemon-reload || true

			echo "Removing ollama binary..."
			rm -f "${BINARY_PATH}"

			echo "Removing ollama group..."
			userdel ollama || true
			groupdel ollama || true

			echo "Removing ollama lib folder..."
			rm -rf "${INSTALL_PATH}"
			rm -rf /usr/share/ollama
		fi
	;;

esac
exit 0
