#!/bin/sh

set -e

status() {
   state=$1
   shift
   case "${state}" in
      RUN) color_number=6 ;;
      PASS) color_number=2 ;;
      FAIL) color_number=1 ;;
   esac
   color=
   reset=
   if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && command -v tput >/dev/null 2>&1; then
      color_count=$(tput colors 2>/dev/null || printf '0')
      case "${color_count}" in
         ''|*[!0-9]*) color_count=0 ;;
      esac
      if [ "${color_count}" -ge 8 ]; then
         color=$(tput setaf "${color_number}" 2>/dev/null || :)
         reset=$(tput sgr0 2>/dev/null || :)
      fi
   fi
   printf '%s[%s]%s %s\n' "${color}" "${state}" "${reset}" "$*"
}

cat <<EOS > input.txt
SentencePiece is an unsupervised text tokenizer and detokenizer mainly
for Neural Network-based text generation systems where the vocabulary
size is predetermined prior to the neural model
training. SentencePiece implements subword units (e.g.,
byte-pair-encoding (BPE) [Sennrich et al.]) and unigram language model
[Kudo.]) with the extension of direct training from raw
sentences. SentencePiece allows us to make a purely end-to-end system
that does not depend on language-specific pre/postprocessing.
EOS

rm -f tiny.*
status RUN "Train a temporary model"
if spm_train --input=input.txt --model_prefix=tiny --vocab_size=100 --character_coverage=1.0 >/dev/null 2>&1; then
   status PASS "Train a temporary model"
else
   status FAIL "Train a temporary model"
   exit 1
fi

input="I saw a girl with a telescope."
status RUN "Encode input"
if encoded=$(printf '%s\n' "${input}" | spm_encode --model=tiny.model); then
   :
else
   status FAIL "Encode input"
   exit 1
fi
if [ -z "${encoded}" ]; then
   status FAIL "spm_encode returned no output"
   exit 1
fi
status PASS "Encode input"

status RUN "Decode encoded output"
if decoded=$(printf '%s\n' "${encoded}" | spm_decode --model=tiny.model --input_format=piece); then
   :
else
   status FAIL "Decode encoded output"
   exit 1
fi
if [ "${input}" = "${decoded}" ]; then
   status PASS "spm_encode round-trip"
else
   status FAIL "Round-trip mismatch: <${decoded}>"
   exit 1
fi
rm -f input.txt
rm -f tiny.*
