#!/bin/sh

set -e
test -n "$VERBOSE" && set -x

if test -f "$1"/VERSION && test $(cat "$1"/VERSION) = $2; then
  exit
fi

if command -v git >/dev/null; then
  GIT="tea git"
else
  GIT=git
fi

mkdir -p "$1"
cd "$1"

tea gum format "# preparing for model fetch"
echo  # spacer

URL=$(curl -Ssf \
  https://raw.githubusercontent.com/ItsPi3141/alpaca.cpp/master/README.md | \
  grep -o 'magnet:[^`]*')

if test -d trackers; then
  $GIT -C trackers fetch origin
  $GIT -C trackers reset --hard origin/master
else
  $GIT clone "https://github.com/ngosang/trackerslist" trackers
fi

TRACKERS=$(grep -v '^#' "trackers/trackers_all.txt" | tr '\n' ',')

tea gum format <<EoMD
# downloading 4b quantized LLaMA (7B) model
models will be placed: \`$PWD\`
> this may take a a few minutes…
EoMD

tea aria2c \
  --dir=. \
  --seed-time=0 \
  --bt-tracker="$TRACKERS" \
  --summary-interval=0 \
  --check-integrity \
  "$URL"

echo $2 > VERSION

tea gum format "# All done!"
echo  #spacer
