#!/data/data/com.termux/files/usr/bin/bash
set -u
limit_lines=120
limit_bytes=10000
clip_bytes=4000
remote_host=zume

usage() { printf 'usage: ppp [-n] [zume] "msg [&tt& commit suffix]" command...\n       ppp [-n] [zume] "msg" < stdin\n       ppp -v\n' >&2; }

if [ "${1:-}" = "-v" ]; then
  echo "ppp 1.4.0"
  exit 0
fi

if [ "${1:-}" = "-n" ]; then
  PPP_NO_PAUSE=1
  shift
else
  PPP_NO_PAUSE=0
fi

[ "$#" -eq 0 ] && [ -t 0 ] && { usage; exit 0; }

is_remote=0
if [ "$#" -gt 0 ] && [ "$1" = "$remote_host" ]; then is_remote=1; shift; fi

[ "$#" -eq 0 ] && { usage; exit 1; }
msg=$1; shift

if [ "$#" -eq 0 ]; then
  [ -t 0 ] && { usage; exit 1; }
  SRC=$(cat)
else
  SRC="$*"
fi
[ -z "${SRC:-}" ] && { usage; exit 1; }

export PPP_LEVEL=$(( ${PPP_LEVEL:-0} + 1 ))

if [ -t 1 ]; then
  TEAL='\033[38;5;43m'
  NC='\033[0m'
else
  TEAL='' NC=''
fi

# PARSE-START
commit_msg="$msg"
tt_desc="${msg%%&tt&*}"
trim() {
  local s="$1"
  s="${s#"${s%%[![:space:]]*}"}"
  s="${s%"${s##*[![:space:]]}"}"
  printf '%s' "$s"
}
tt_desc=$(trim "$tt_desc")
commit_msg=$(trim "$commit_msg")
# PARSE-END

local_before=""
git_root=""
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  local_before=$(git status --porcelain)
  git_root=$(git rev-parse --show-toplevel)
fi

zume_before=""
if [ "$is_remote" -eq 1 ]; then
  zume_before=$(ssh "$remote_host" 'cd /root/ahoxus.org 2>/dev/null && git status --porcelain' 2>/dev/null)
fi

stamp=$(date +%Y%m%d-%H%M%S)
local_dir="$HOME/ppp-output"
local_file="$local_dir/$stamp.txt"
mkdir -p "$local_dir" "$HOME/.tmp"
tmp_file="$HOME/.tmp/ppp-last.$$"
disp_file="$HOME/.tmp/ppp-disp.$$"
clip_file="$HOME/.tmp/ppp-clip.$$"

if [ "$is_remote" -eq 1 ]; then
  remote_file="\$HOME/ppp-output/$stamp.txt"
  printf '%s\n' "$SRC" | ssh "$remote_host" 'mkdir -p "$HOME/ppp-output"; exec sh' >"$tmp_file" 2>&1
else
  eval "$SRC" >"$tmp_file" 2>&1
fi
status=$?

bytes=$(wc -c <"$tmp_file")
lines=$(wc -l <"$tmp_file")
cp "$tmp_file" "$local_file"

if [ "$bytes" -gt "$limit_bytes" ] || [ "$lines" -gt "$limit_lines" ]; then
  if [ "$is_remote" -eq 1 ]; then
    ssh "$remote_host" "cat > \"$remote_file\"" <"$tmp_file"
  fi
  {
    if [ "$is_remote" -eq 1 ]; then
      printf 'capped: %sl/%sb. full: %s | %s\n\n' "$lines" "$bytes" "$local_file" "$remote_file"
    else
      printf 'capped: %sl/%sb. full: %s\n\n' "$lines" "$bytes" "$local_file"
    fi
    sed -n '1,80p' "$tmp_file"
    printf '\n... clipped ...\n\n'
    tail -20 "$tmp_file"
  } > "$disp_file"
  cat "$disp_file"
else
  cp "$tmp_file" "$disp_file"
  cat "$disp_file"
fi

test_result="none"
test_path=""
test_log=""
if [ -n "$tt_desc" ]; then
  if [ "$is_remote" -eq 1 ]; then
    search_dirs=""
    ssh "$remote_host" '[ -d /root/forge/tt ]' 2>/dev/null && search_dirs="$search_dirs /root/forge/tt"
    ssh "$remote_host" '[ -d /root/forge/bats ]' 2>/dev/null && search_dirs="$search_dirs /root/forge/bats"
    if [ -n "$search_dirs" ]; then
      test_path=$(ssh "$remote_host" "grep -rl -i '# tt:' $search_dirs 2>/dev/null | xargs grep -l -i '$tt_desc' 2>/dev/null | head -1" 2>/dev/null || true)
    fi
    if [ -z "$test_path" ]; then
      tt_desc_dash="${tt_desc// /-}"
      test_path=$(ssh "$remote_host" "ls /root/forge/tt/tt-*${tt_desc_dash}*.sh /root/forge/bats/tt-*${tt_desc_dash}*.sh 2>/dev/null | head -1" 2>/dev/null || true)
    fi
    if [ -z "$test_path" ]; then
      test_path=$(grep -oE '/[^ ]+\.sh' "$tmp_file" 2>/dev/null | head -1 || true)
    fi
    if [ -n "$test_path" ]; then
      ssh "$remote_host" "$test_path" >/dev/null 2>&1 && test_result="green" || test_result="red"
      test_log="test found: $test_path"
    else
      test_log="test not found on zume"
    fi
  else
    search_dirs=""
    if [ -n "$git_root" ]; then
      [ -d "$git_root/forge/tt" ] && search_dirs="$search_dirs $git_root/forge/tt"
      [ -d "$git_root/forge/bats" ] && search_dirs="$search_dirs $git_root/forge/bats"
    fi
    if [ -z "$search_dirs" ]; then
      [ -d "./forge/tt" ] && search_dirs="$search_dirs ./forge/tt"
      [ -d "./forge/bats" ] && search_dirs="$search_dirs ./forge/bats"
    fi
    if [ -n "$search_dirs" ]; then
      test_path=$(grep -rl -i '# tt:' $search_dirs 2>/dev/null | xargs grep -l -i "$tt_desc" 2>/dev/null | head -1 || true)
    fi
    if [ -z "$test_path" ] && [ -n "$git_root" ]; then
      tt_desc_dash="${tt_desc// /-}"
      test_path=$(ls "$git_root/forge/tt/tt-"*"${tt_desc_dash}"*.sh "$git_root/forge/bats/tt-"*"${tt_desc_dash}"*.sh 2>/dev/null | head -1 || true)
    fi
    if [ -z "$test_path" ]; then
      test_path=$(grep -oE '/[^ ]+\.sh' "$tmp_file" 2>/dev/null | head -1 || true)
    fi
    if [ -n "$test_path" ]; then
      bash "$test_path" >/dev/null 2>&1 && test_result="green" || test_result="red"
      test_log="test found: $test_path"
    else
      test_log="test not found"
    fi
  fi
fi

set_clip() {
  if command -v xcp >/dev/null 2>&1; then xcp "$1"
  elif command -v termux-clipboard-set >/dev/null 2>&1; then printf '%s' "$1" | termux-clipboard-set; fi
}


# FOOT-START
if [ "$test_result" = "red" ]; then
  foot="[ppp] test failed 🔴 $tt_desc"$'\n'
  foot="${foot}[log] $test_log"$'\n'
  if [ -n "$TEAL" ]; then
    printf "${TEAL}\n%s${NC}" "$foot"
  else
    printf '\n%s' "$foot"
  fi
  { cat "$disp_file"; printf '\n%s' "$foot"; } > "$clip_file"
  current_clip=$(cat "$clip_file")

  old_clip=""
  if command -v termux-clipboard-get >/dev/null 2>&1; then
    old_clip=$(termux-clipboard-get 2>/dev/null || true)
  fi

  if [ -n "$old_clip" ]; then
    sep=$'\n\n--- ppp ---\n\n'
    new_clip="${old_clip}${sep}${current_clip}"
  else
    new_clip="$current_clip"
  fi
  set_clip "$new_clip"

  if [ "$PPP_NO_PAUSE" -eq 1 ]; then
    rm -f "$tmp_file" "$disp_file" "$clip_file"
    exit 1
  fi

  printf '[error — q clears, other key keeps] '
  rm -f "$tmp_file" "$disp_file" "$clip_file"
  read -rn 1 K < /dev/tty 2>/dev/null || true
  echo
  if [ "$K" = "q" ]; then
    clear 2>/dev/null || true
  fi
  exit 1
fi

local_msg=""
if [ -n "$git_root" ]; then
  d=$(git status --porcelain)
  if [ -n "$local_before" ]; then
    [ -n "$d" ] && local_msg="dirt(old): skipped"
  elif [ "$status" -eq 0 ] && [ -n "$d" ]; then
    git add -A >/dev/null 2>&1
    if git commit -q -m "$commit_msg" >/dev/null 2>&1; then
      git push -q --all origin >/dev/null 2>&1 || true
      git push -q --all backup >/dev/null 2>&1 || true
      local_msg="forged"
    else
      local_msg="commit-fail"
    fi
  elif [ -n "$d" ]; then
    local_msg="dirt"
  fi
fi

zume_msg=""
if [ "$is_remote" -eq 1 ]; then
  dnow=$(ssh "$remote_host" 'cd /root/ahoxus.org 2>/dev/null && git status --porcelain' 2>/dev/null)
  if [ -n "$zume_before" ]; then
    [ -n "$dnow" ] && zume_msg="dirt(old): skipped"
  elif [ -n "$dnow" ] && [ "$status" -eq 0 ]; then
    esc=$(printf '%s' "$commit_msg" | sed "s/'/'\\''/g")
    ssh "$remote_host" 'cd /root/ahoxus.org 2>/dev/null || exit 0; git add -A >/dev/null 2>&1; git commit -q -m '"'"'"'"'"'"'"'"'"$esc'"'"'"'"'"'"'"'"' >/dev/null 2>&1 && { git push -q --all origin >/dev/null 2>&1; git push -q --all backup >/dev/null 2>&1; }' 2>/dev/null
    zume_msg="forged"
  elif [ -n "$dnow" ]; then
    zume_msg="dirt"
  fi
fi

forge_parts=()
[ -n "$local_msg" ] && [ "$local_msg" != "forged" ] && forge_parts+=("loc:$local_msg")
[ -n "$zume_msg" ] && [ "$zume_msg" != "forged" ] && forge_parts+=("zum:$zume_msg")

if [ "$status" -eq 0 ] && [ "$test_result" = "green" ]; then
  foot="[ppp] ok 🟢 $tt_desc"$'\n'
elif [ "$status" -eq 0 ]; then
  foot="[ppp] ok"$'\n'
else
  foot="[ppp] unexpected error $status"$'\n'
  [ "$test_result" = "green" ] && foot="${foot}[msg] 🟢 $commit_msg"$'\n'
fi

if [ -n "$tt_desc" ] && [ "$test_result" = "none" ]; then
  foot="${foot}[warn] tt desc given but no test found: $tt_desc"$'\n'
fi
if [ ${#forge_parts[@]} -gt 0 ]; then
  fjoined=$(IFS=' · '; printf '%s' "${forge_parts[*]}")
  foot="${foot}[forge] $fjoined"$'\n'
fi

if [ -n "$TEAL" ]; then
  printf "${TEAL}\n%s${NC}" "$foot"
else
  printf '\n%s' "$foot"
fi

{ cat "$disp_file"; printf '\n%s' "$foot"; } > "$clip_file"
current_clip=$(cat "$clip_file")

old_clip=""
if command -v termux-clipboard-get >/dev/null 2>&1; then
  old_clip=$(termux-clipboard-get 2>/dev/null || true)
fi

if [ -n "$old_clip" ]; then
  sep=$'\n\n--- ppp ---\n\n'
  new_clip="${old_clip}${sep}${current_clip}"
else
  new_clip="$current_clip"
fi
set_clip "$new_clip"

if [ "$PPP_NO_PAUSE" -eq 1 ]; then
  rm -f "$tmp_file" "$disp_file" "$clip_file"
  exit "$status"
fi

printf '[appended — q clears, other key keeps] '
rm -f "$tmp_file" "$disp_file" "$clip_file"
read -rn 1 K < /dev/tty 2>/dev/null || true
echo

if [ "$K" = "q" ]; then
  clear 2>/dev/null || true
fi

exit "$status"
# FOOT-END
