#!/usr/bin/env bash
# Acceptance check 8 of CARD.md: the crop column and the layout, in a real
# terminal. Needs tmux. In a throwaway HOME it rests four fresh directories made
# of real files, on the real clock, inside a tmux pane, captures the pane and a
# piped `fallow status`, and checks that CROP is last, aligned and in rotation.
# The same session runs again at 44 columns, the width of a phone terminal.
# Captures go to out/pane-<width>-<scene>.txt for test/shots.py.
# From the project folder: bash test/pane.sh
set -u
export LC_ALL=C
cd "$(dirname "$0")/.."
SRC=$PWD
mkdir -p out
BIN=$(mktemp -d)
CGO_ENABLED=0 go build -o "$BIN/fallow" . || exit 1
command -v tmux > /dev/null || { echo "tmux is needed for this check" >&2; exit 1; }

pass=0; fails=0
t() { # description, then a test command
  local d=$1; shift
  if "$@"; then pass=$((pass + 1)); echo "  ok  $d"; else fails=$((fails + 1)); echo "  FAIL  $d"; fi
}

# session WIDTH: one real session in its own HOME and tmux server.
session() {
  local w=$1
  export HOME=$(mktemp -d)
  local T="tmux -L fallow-$w -f /dev/null"
  # the fields: this source as a git repository, the shell skeleton, a time
  # zone directory and the tmux documentation, all copied from this machine
  mkdir $HOME/src $HOME/skel $HOME/tz $HOME/docs
  cp -R $SRC/go.mod $SRC/*.go $SRC/README.md $SRC/test $HOME/src/
  git -C $HOME/src init -q && git -C $HOME/src add -A && git -C $HOME/src -c user.name=t -c user.email=t@t commit -qm 'fallow source'
  cp -R /etc/skel/. $HOME/skel/
  cp -R /usr/share/zoneinfo/Europe/. $HOME/tz/
  cp -R /usr/share/doc/tmux/. $HOME/docs/
  cat > $HOME/.rc <<EOF
export PATH=$BIN:/usr/bin:/bin LC_ALL=C GIT_PAGER=cat PAGER=cat
PS1='\$ '
PROMPT_COMMAND='tmux wait-for -S ready'
cd ~
EOF
  $T new-session -d -s f -x $w -y 120 "bash --rcfile $HOME/.rc --noprofile -i"
  $T set -g status off
  # ready: the prompt command has run and readline has drawn "$ ", so keys
  # typed next are read by the shell, not echoed early by the terminal
  ready() {
    $T wait-for ready
    for _ in $(seq 100); do
      [ "$($T display -p -t f '#{cursor_x}')" = 2 ] && [ "$($T capture-pane -p -t f | sed '/^$/d' | tail -n 1)" = '$' ] && return
      sleep 0.05
    done
  }
  ready
  typ() { $T send-keys -t f -l "$1"; $T send-keys -t f Enter; ready; }
  shot() { $T capture-pane -p -t f | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' > out/pane-$w-$1.txt; }
  clear_pane() { typ clear; $T clear-history -t f; }

  clear_pane
  typ 'fallow rest ~/src --seasons 2'
  typ 'echo x >> ~/src/main.go'
  typ 'cat ~/src/go.mod'
  typ 'git -C ~/src log --oneline'
  typ 'fallow plough ~/src'
  typ 'echo $?'
  shot first
  # observed, not promised: what git status does inside a read-only .git
  git -C $HOME/src status --short > $HOME/.gitstatus 2>&1; echo "exit $?" >> $HOME/.gitstatus
  clear_pane
  typ 'fallow rest ~/skel --seasons 1'
  typ 'fallow rest ~/tz --seasons 4'
  typ 'fallow plough ~/skel --trespass'
  typ 'fallow rest ~/docs --seasons 1'
  sleep 1
  typ 'chmod u+w ~/src/main.go && echo >> ~/src/main.go'
  shot season
  clear_pane
  typ 'fallow status'
  shot status
  fallow_status=$($BIN/fallow status)
  printf '%s\n' "$fallow_status" > out/status-$w.txt
  clear_pane
  typ 'cp -a ~/tz ~/tz-copy'
  typ 'fallow status ~/tz-copy'
  typ 'chmod u+w ~/tz-copy/Paris'
  typ 'fallow status ~/tz-copy'
  typ 'fallow status ~/src'
  typ 'fallow plough ~/tz-copy'
  shot copy
  cp $HOME/.fallow-book out/book-$w.txt
  cp $HOME/.gitstatus out/gitstatus-$w.txt
  $T kill-server
  chmod -R u+w $HOME && rm -rf $HOME
}

# table FILE: the header and the four rows of the status table in FILE, and
# every assertion of check 8 on them.
table() {
  local f=$1 hdr off i=0 row
  hdr=$(grep -m1 '^FIELD  ' $f)
  t "$f: header FIELD RESTED SEASONS PLOUGH FROM STATE CROP" eval '[ "$(echo "$hdr" | tr -s " ")" = "FIELD RESTED SEASONS PLOUGH FROM STATE CROP" ]'
  off=$(awk -v h="$hdr" 'BEGIN{print index(h, "CROP")}')
  t "$f: CROP is the last column (offset $off)" eval '[ "${hdr:$((off - 1))}" = CROP ]'
  for want in "winter grain" "spring grain" "fallow" "winter grain"; do
    i=$((i + 1))
    row=$(grep -A4 -m1 '^FIELD  ' $f | sed -n "$((i + 1))p")
    t "$f: row $i ends with '$want' at offset $off" eval '[ "${row:$((off - 1))}" = "$want" ]'
  done
  t "$f: no fifth row" eval '[ -z "$(grep -A5 -m1 "^FIELD  " $f | sed -n 6p)" ]'
}

echo "== 8. The crop column and layout, in a real terminal"
session 100
table out/pane-100-status.txt
table out/status-100.txt
t "status.txt has no escape bytes" [ "$(grep -c $'\x1b' out/status-100.txt)" = 0 ]
t "the book never says grain" [ "$(grep -ci grain out/book-100.txt)" = 0 ]
t "no rest or plough output says winter or spring grain" eval "! grep -qE 'winter grain|spring grain' out/pane-100-first.txt out/pane-100-season.txt out/pane-100-copy.txt"
t "the pane is as wide as the table, no row wraps" eval '[ "$(awk "length > 100" out/pane-100-status.txt | wc -l)" = 0 ]'
t "a write is refused in the resting field" grep -qF 'src/main.go: Permission denied' out/pane-100-first.txt
t "git log reads it" grep -qE '^[0-9a-f]{7} .*fallow source$' out/pane-100-first.txt
t "the early plough refusal, exit 1" eval "grep -qE '^Not before 24 Jun 2027\. [0-9]+ days to go\. Nothing was changed\.$' out/pane-100-first.txt && grep -A1 -F '$ echo \$?' out/pane-100-first.txt | grep -qx 1"
t "the copy carries the locks of entry 3" grep -qE '^~/tz-copy is not in the book\. It carries the locks of entry 3 \(~/tz\): ([0-9]+) of \1 locked entries\.$' out/pane-100-copy.txt
t "status shows the change and the caution" eval "grep -qF '  Changed since rest: 1 entry. Newest: ' out/pane-100-status.txt && sed '\$d' out/pane-100-status.txt | tail -n 1 | grep -qxF 'A modification time can be moved by a backup, a sync or an indexer. This is evidence, not a finding.'"
echo "  git status inside the read-only .git (observed, not promised):"; sed 's/^/  > /' out/gitstatus-100.txt

echo; echo "== the same session at 44 columns"
session 44
table out/status-44.txt
t "44 columns: no line is wider than the pane" eval '[ "$(cat out/pane-44-*.txt | awk "length > 44" | wc -l)" = 0 ]'

chmod -R u+w "$BIN" 2>/dev/null; rm -rf "$BIN"
echo
if [ $fails = 0 ]; then echo "all $pass assertions passed"; else echo "$fails of $((pass + fails)) assertions FAILED"; fi
[ $fails = 0 ]
