#!/usr/bin/env bash
set -euo pipefail

REPO_URL="https://github.com/devshane/zork.git"
REPO_DIR="${REPO_DIR:-$PWD/zork}"
DO_REBUILD=0
DO_FORCE_RECLONE=0
DO_UNINSTALL=0

usage() {
  cat <<EOF
Usage: $0 [--rebuild] [--force-reclone] [--uninstall]

  --rebuild         Clean and rebuild existing tree after patching
  --force-reclone   Remove existing ./zork and clone fresh
  --uninstall       Delete ./zork and exit
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --rebuild) DO_REBUILD=1; shift;;
    --force-reclone) DO_FORCE_RECLONE=1; shift;;
    --uninstall) DO_UNINSTALL=1; shift;;
    -h|--help) usage; exit 0;;
    *) echo "Unknown arg: $1"; usage; exit 1;;
  esac
done

msg() { printf "\033[1;34m>>\033[0m %s\n" "$*"; }
ok()  { printf "\033[1;32m✔\033[0m %s\n" "$*"; }

if [[ $DO_UNINSTALL -eq 1 ]]; then
  if [[ -d "$REPO_DIR" ]]; then
    rm -rf "$REPO_DIR"
    ok "Removed $REPO_DIR"
  else
    msg "Nothing to remove at $REPO_DIR"
  fi
  exit 0
fi

if [[ $DO_FORCE_RECLONE -eq 1 && -d "$REPO_DIR" ]]; then
  msg "Forcing fresh clone: removing $REPO_DIR"
  rm -rf "$REPO_DIR"
fi

# Clone or update
if [[ ! -d "$REPO_DIR/.git" ]]; then
  msg "Cloning $REPO_URL into $REPO_DIR"
  git clone "$REPO_URL" "$REPO_DIR"
else
  msg "Updating existing repo in $REPO_DIR"
  git -C "$REPO_DIR" fetch --depth=1 origin
  # Use the default branch from origin
  DEFAULT_BRANCH="$(git -C "$REPO_DIR" symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@')"
  git -C "$REPO_DIR" reset --hard "origin/${DEFAULT_BRANCH}"
fi

cd "$REPO_DIR"
PROJECT_DIR="$(pwd)"

# Patch Makefile (idempotent)
msg "Patching Makefile (drop termcap, add -DNO_TERMCAP, fix TEXTFILE path)"
# 1) Drop -ltermcap/-ltinfo/-lncurses from link flags
sed -i 's/-ltermcap//g; s/-ltinfo//g; s/-lncurses//g' Makefile

# 2) Ensure -DNO_TERMCAP in CFLAGS (add only once)
if grep -qE '^[[:space:]]*CFLAGS[[:space:]]*=' Makefile; then
  if ! grep -q -- '-DNO_TERMCAP' Makefile; then
    sed -i 's/^\([[:space:]]*CFLAGS[[:space:]]*=[^#\n]*\)/\1 -DNO_TERMCAP/' Makefile
  fi
else
  echo 'CFLAGS += -DNO_TERMCAP' >> Makefile
fi

# 3) Fix TEXTFILE to local dtextc.dat
ESC_PATH="$(printf '%s' "$PROJECT_DIR/dtextc.dat" | sed 's/[.[\*^$(){}+?|/]/\\&/g')"
if grep -q 'DTEXTFILE=' Makefile; then
  sed -i "s#-DTEXTFILE=\\\".*dtextc\.dat\\\"#-DTEXTFILE=\\\"$ESC_PATH\\\"#g" Makefile
fi

# Add NO_TERMCAP stubs to supp.c (idempotent)
if ! grep -q 'NO_TERMCAP fallback' supp.c; then
  msg "Injecting NO_TERMCAP fallback into supp.c"
  cat >> supp.c <<'EOF'

/* ---- NO_TERMCAP fallback ---------------------------------------------- */
#ifdef NO_TERMCAP
#ifdef abs
#undef abs
#endif
#include <stdlib.h>
#include <string.h>

/* Match old prototypes used in this codebase (void return is fine here). */
void tgetent(char *bp, const char *name) { (void)bp; (void)name; }

/* Provide rows/cols via env or defaults; unknown caps -> -1 */
int tgetnum(const char *id) {
    if (strcmp(id, "li") == 0) {
        const char *e = getenv("LINES");
        return e ? atoi(e) : 24;
    }
    if (strcmp(id, "co") == 0) {
        const char *e = getenv("COLUMNS");
        return e ? atoi(e) : 80;
    }
    return -1;
}
#endif
/* ----------------------------------------------------------------------- */
EOF
fi

# Ensure <unistd.h> is included in local.c for getuid (idempotent)
if ! grep -q '^#include <unistd.h>' local.c; then
  msg "Adding #include <unistd.h> to local.c"
  sed -i '1i #include <unistd.h>' local.c
fi

# Build
msg "Building Zork"
make clean || true
make

ok "Build complete:"
echo "  Binary : $PROJECT_DIR/zork"
echo "  Data   : $PROJECT_DIR/dtextc.dat"
echo
echo "Run it like:"
echo "  cd \"$PROJECT_DIR\" && ./zork"
echo
echo "Options:"
echo "  $0 --rebuild         # clean + rebuild"
echo "  $0 --force-reclone   # delete and reclone fresh"
echo "  $0 --uninstall       # remove the repo"
