db := 'db/game.rec'

# show all commands
default:
  just --list --unsorted

# super plain boring output
_map:
  recsel -t game {{db}} | recfmt '"{{{{name}}": "{{{{id}}", '

# build dot file (tmp file)
_dot:
  make dot

# build data object (tmp file)
_data:
  make data

# build a graph of all the nodes
graph:
  make graph

# plain output
build: _data
  mustache tmp/data {{db}} \
  | recfmt '{{{{id}}: {{{{text}}|' \
  | sed -e 's/|/\n\n/g' \

# read the story
browse:
  just build | fmt | less

# remove generated files
clean:
  rm -f tmp/* out/*

# word count and number of nodes
info:
  echo "$(recinf -t game {{db}}) nodes" \
  && echo "$(recsel -t game -P text {{db}} | wc -w | awk '{ print $1}') words"

# rebulid graph on change
watch-graph:
  ls {{db}} | entr -c just graph

# rebulid pdf on change
watch-pdf:
  ls {{db}} | entr -c just pdf

# shuffle ids
_shuffle:
  recsel -t game -P id -C db/game.rec \
  | shuf --random-source=/dev/urandom \
  | gsed -e '/^0$/d' -e '1 i 0'

# story in random order, starting with 0
randomize:
  for n in $(just _shuffle); do recsel -t game -e "id='$n'" db/game.rec; echo; done

# renumber the randomized list
renumber:
  #!/usr/bin/env zsh
  tmpfile=$(mktemp)
  echo "$tmpfile"
  cp {{db}} {{db}}.bak
  just randomize > "$tmpfile"
  j=$(recinf -t game "$tmpfile")
  recdel -t game -n 0-$((j - 1)) {{db}}
  for i in {0..$((j - 1))}
  do
    name=$(recsel -n "$i" -P name "$tmpfile")
    text=$(recsel -n "$i" -P text "$tmpfile")
    #echo "$i $name $text"
    recins -t game -f name -v "$name" -f text -v "$text" {{db}}
  done
  rm "$tmpfile"

# make ms
_ms: 
  make ms

# make pdf
pdf:
  make pdf

# make ascii doc
ascii:
  make ascii

# make twee
twee:
  #!/usr/bin/env zsh
  exec > out/story.twee
  cat<<EOF
  :: StoryTitle
  CORNQUEST
  
  :: StoryData
  {
    "start": "beginning",
    "ifid": "BDB6BEED-D6E0-4F71-9227-A8AD27067935"
  }

  EOF
  mustache tmp/data <(sed 's/{{{{\([^}]*\)}}/[[{{{{\1}}|\1]]/g' {{db}}) | recsel -t game | recfmt -f templates/twee.template

# make twine html
html: twee
  tweego --format=harlowe-3 --output=out/story.html out/story.twee

# make twine json
json: twee
  tweego --format=twison --output=out/json.html out/story.twee

# generate tags
tags:
  make tags