#!/usr/bin/env ruby
#
# Updates all Ollama models to their latest versions.
#
# This script fetches all available models from the configured Ollama instance
# and pulls the latest version of each model. It handles errors gracefully,
# continuing to update remaining models even if one fails.
#
# Environment Variables:
#   - OLLAMA_HOST: Hostname for the Ollama server (default: 'localhost')
#   - OLLAMA_URL: Full URL for the Ollama server (overrides OLLAMA_HOST)

require 'time'
require 'term/ansicolor'
include Term::ANSIColor
require 'ollama'
include Ollama

base_url = ENV['OLLAMA_URL'] || 'http://%s' % ENV.fetch('OLLAMA_HOST')
ollama = Client.new(base_url:)
ollama.tags.models.each do |model|
  name, modified_at = model.name, Time.parse(model.modified_at)
  infobar.puts(
    "Updating model #{bold {name}} (last modified at #{modified_at.iso8601}):"
  )
  ollama.pull(model: name)
rescue Ollama::Errors::Error => e
  infobar.puts "Caught #{e.class} for model #{bold { model.name }}: #{e} => Continuing."
end
