#!/usr/bin/env bash
# ============================================================================
#  Daylight code-setup
#  One-shot Termux -> proot Debian web-dev environment for an Android tablet.
#
#  Run inside Termux (installed from F-Droid, NOT the Play Store):
#       curl -fsSL https://code.daylightcomputer.com | bash
#
#  Installs: proot Debian, Node LTS, Bun, Claude Code, Codex CLI, opencode.
#
#  After it finishes:  type  deb  to enter Debian,  then  newapp myapp  to
#  scaffold a React app, then  cd ~/projects/myapp && npm run dev  and open
#  http://localhost:5173 in the tablet's browser.  Type  claude  to start
#  Claude Code (first run opens a browser login; press c to copy the URL).
# ============================================================================

set -euo pipefail

main() {

DISTRO="debian"

say() { printf '\n\033[1m== %s\033[0m\n' "$*"; }

# ---------------------------------------------------------------------------
# 0. Sanity: are we actually in Termux?
# ---------------------------------------------------------------------------
if [ -z "${PREFIX:-}" ] || [ ! -d "$PREFIX/var/lib" ]; then
  echo "This must be run inside Termux. Install Termux from F-Droid first."
  exit 1
fi

# ---------------------------------------------------------------------------
# 1. Termux base packages
# ---------------------------------------------------------------------------
say "Updating Termux and installing base packages"
yes | pkg update -y || true
yes | pkg upgrade -y || true
# proot-distro is essential — fail loudly if it can't be installed
pkg install -y proot-distro
pkg install -y git curl wget openssh nano which || true

# Keep the device awake so a dev server isn't killed when the screen sleeps
termux-wake-lock || true

# Optional: give Termux access to shared storage (you'll get a permission prompt)
termux-setup-storage || true

# ---------------------------------------------------------------------------
# 2. Theme Termux itself  (high-contrast b/w e-ink + tablet extra-keys row)
# ---------------------------------------------------------------------------
say "Theming Termux (e-ink palette + dev keys row)"
mkdir -p "$HOME/.termux"

# High-contrast black-on-white for e-ink: pure white background, pure black
# text, and every ANSI color mapped to black/gray so nothing renders as a
# faint mid-tone.
cat > "$HOME/.termux/colors.properties" <<'COLORS'
background=#ffffff
foreground=#000000
cursor=#000000
color0=#000000
color1=#000000
color2=#000000
color3=#000000
color4=#000000
color5=#000000
color6=#000000
color7=#555555
color8=#555555
color9=#000000
color10=#000000
color11=#000000
color12=#000000
color13=#000000
color14=#000000
color15=#ffffff
COLORS

# Large font for the e-ink tablet. Termux keeps font size in shared prefs,
# not termux.properties — and the two Termux lineages disagree on where:
#   F-Droid build:     com.termux_preferences.xml, <string name="fontsize">
#   Play Store build:  app.TermuxActivity.xml,     <int name="font_size">
# Write both (best-effort). Applies on next app start; note a session change
# before exit can flush the old in-memory value back over the file.
FONTSIZE=40
PREFS_DIR="$(dirname "$(dirname "$PREFIX")")/shared_prefs"
if mkdir -p "$PREFS_DIR" 2>/dev/null; then
  # F-Droid build
  PREFS_FILE="$PREFS_DIR/com.termux_preferences.xml"
  if [ -f "$PREFS_FILE" ] && grep -q 'name="fontsize"' "$PREFS_FILE"; then
    sed -i "s|<string name=\"fontsize\">[0-9]*</string>|<string name=\"fontsize\">$FONTSIZE</string>|; s|<int name=\"fontsize\" value=\"[0-9]*\" */>|<int name=\"fontsize\" value=\"$FONTSIZE\" />|" "$PREFS_FILE" || true
  elif [ -f "$PREFS_FILE" ]; then
    sed -i "s|</map>|    <string name=\"fontsize\">$FONTSIZE</string>\n</map>|" "$PREFS_FILE" || true
  else
    printf '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n    <string name="fontsize">%s</string>\n</map>\n' "$FONTSIZE" > "$PREFS_FILE" || true
  fi
  # Play Store build (font_size may carry a per-display suffix, e.g. font_size2)
  PREFS_FILE="$PREFS_DIR/app.TermuxActivity.xml"
  if [ -f "$PREFS_FILE" ] && grep -q 'name="font_size' "$PREFS_FILE"; then
    sed -i "s|<int name=\"font_size\([0-9]*\)\" value=\"[0-9]*\" */>|<int name=\"font_size\1\" value=\"$FONTSIZE\" />|g" "$PREFS_FILE" || true
  elif [ -f "$PREFS_FILE" ]; then
    sed -i "s|</map>|    <int name=\"font_size\" value=\"$FONTSIZE\" />\n</map>|" "$PREFS_FILE" || true
  else
    printf '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n    <int name="font_size" value="%s" />\n</map>\n' "$FONTSIZE" > "$PREFS_FILE" || true
  fi
fi

# Extra keys row: ESC/TAB/CTRL/ALT, slash, dash, pipe, arrows — huge on a tablet.
# terminal-margin-*: padding (dp) around terminal content. F-Droid build only —
# the Play Store build ignores these. Needs a full Termux restart.
cat > "$HOME/.termux/termux.properties" <<'PROPS'
extra-keys = [ \
 ['ESC','/','-','|','HOME','UP','END','PGUP'], \
 ['TAB','CTRL','ALT','~','LEFT','DOWN','RIGHT','PGDN'] \
]
terminal-margin-horizontal=24
terminal-margin-vertical=24
fullscreen = true
PROPS

termux-reload-settings || true

# Friendly Termux aliases / entry points
touch "$HOME/.bashrc"
grep -q "alias deb=" "$HOME/.bashrc" 2>/dev/null || cat >> "$HOME/.bashrc" <<'TBRC'

# --- vibecode helpers ---
alias deb='proot-distro login debian'
dev() { proot-distro login debian -- bash -lc 'cd ~/projects 2>/dev/null; exec bash -l'; }
# ------------------------
TBRC

# ---------------------------------------------------------------------------
# 3. Install the Debian guest (idempotent — probed via login, no assumptions
#    about where proot-distro keeps its rootfs)
# ---------------------------------------------------------------------------
if proot-distro login "$DISTRO" -- /bin/true >/dev/null 2>&1; then
  say "$DISTRO guest already working — skipping install"
else
  say "Installing $DISTRO guest (downloads a rootfs — give it a minute)"
  if ! proot-distro install "$DISTRO"; then
    # "already installed" from a broken/partial earlier run — reset reinstalls
    say "Install failed — resetting $DISTRO and reinstalling"
    proot-distro reset "$DISTRO"
  fi
  proot-distro login "$DISTRO" -- /bin/true >/dev/null 2>&1 || {
    echo "Debian guest still not working. Run 'proot-distro remove debian', then re-run this script."
    exit 1
  }
fi

# ---------------------------------------------------------------------------
# 4. Write the inside-Debian setup script to Termux tmp, run it in the guest
#    via --shared-tmp (Termux $TMPDIR appears as /tmp inside Debian).
#    (quoted heredoc: $HOME etc. are expanded INSIDE Debian, not here)
# ---------------------------------------------------------------------------
say "Preparing the inside-Debian setup"
GUEST_SETUP="${TMPDIR:-$PREFIX/tmp}/vibecode-debian-setup.sh"
cat > "$GUEST_SETUP" <<'EOS'
#!/usr/bin/env bash
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive

say() { printf '\n\033[1m  -- %s\033[0m\n' "$*"; }

# Networking under proot on Android: IPv6 sockets often hang, so force apt to
# IPv4, and pin known-good DNS resolvers (the guest's resolv.conf can be empty).
# Note: networks that block outside DNS resolvers (e.g. guest Wi-Fi) will break
# the guest entirely — hop to a hotspot or open network if apt can't connect.
echo 'Acquire::ForceIPv4 "true";' > /etc/apt/apt.conf.d/99force-ipv4
printf 'nameserver 8.8.8.8\nnameserver 1.1.1.1\n' > /etc/resolv.conf

say "Updating Debian and installing build tools"
apt update -y
apt upgrade -y
apt install -y curl wget git build-essential ca-certificates procps file \
               nano less unzip python3

# --- Node via nvm (current LTS; avoids Debian's older system node) ----------
say "Installing Node.js (LTS) via nvm"
export NVM_DIR="$HOME/.nvm"
if [ ! -s "$NVM_DIR/nvm.sh" ]; then
  curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
fi
. "$NVM_DIR/nvm.sh"
nvm install --lts
nvm alias default 'lts/*'
node -v && npm -v

# --- Claude Code (native binary; no Node runtime needed) --------------------
say "Installing Claude Code"
curl -fsSL https://claude.ai/install.sh | bash || true
export PATH="$HOME/.local/bin:$PATH"

# --- OpenAI Codex CLI --------------------------------------------------------
say "Installing OpenAI Codex CLI"
npm install -g @openai/codex || true

# --- opencode ----------------------------------------------------------------
say "Installing opencode"
npm install -g opencode-ai || true

# --- Bun ---------------------------------------------------------------------
say "Installing Bun"
curl -fsSL https://bun.sh/install | bash || true

# --- Starship prompt (the "theme") -----------------------------------------
say "Installing Starship prompt"
curl -fsSL https://starship.rs/install.sh | sh -s -- -y || true

# --- Persist environment for every future login ----------------------------
say "Wiring up shell config"
# Make login shells source .bashrc
cat > "$HOME/.bash_profile" <<'BP'
[ -f "$HOME/.bashrc" ] && . "$HOME/.bashrc"
BP

# Append our block to .bashrc once
if ! grep -q "vibecode block" "$HOME/.bashrc" 2>/dev/null; then
cat >> "$HOME/.bashrc" <<'BRC'

# ===== vibecode block =====
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
export PATH="$HOME/.local/bin:$HOME/.bun/bin:$PATH"
command -v starship >/dev/null && eval "$(starship init bash)"

# Scaffold a fresh Vite + React app:  newapp myapp
newapp() {
  local name="${1:-myapp}"
  mkdir -p "$HOME/projects"; cd "$HOME/projects"
  npm create vite@latest "$name" -- --template react
  cd "$name" && npm install
  echo
  echo "Done. To run it:"
  echo "  cd ~/projects/$name && npm run dev"
  echo "Then open http://localhost:5173 in your browser."
}
# Plain static server in the current folder:  serve [port]
serve() { npx --yes serve -l "${1:-3000}" .; }
# ===== end vibecode block =====
BRC
fi

mkdir -p "$HOME/projects"

say "Inside-Debian setup complete"
EOS

chmod +x "$GUEST_SETUP"

say "Running the inside-Debian setup (this is the long part)"
proot-distro login "$DISTRO" --shared-tmp -- bash "/tmp/$(basename "$GUEST_SETUP")"

# ---------------------------------------------------------------------------
# 5. Done
# ---------------------------------------------------------------------------
cat <<'DONE'

============================================================
  All set. Your tablet is ready to vibe-code.

  Next steps:
    1.  Close and reopen Termux (so the theme + keys load).
    2.  Type:   deb              (enter Debian)
    3.  Type:   newapp myapp     (scaffold a React app)
    4.  Type:   cd ~/projects/myapp && npm run dev
    5.  Open:   http://localhost:5173   in your browser
    6.  Type:   claude           (start Claude Code; first run
                                  opens a browser login — press c
                                  to copy the URL, sign in, paste
                                  the code back)

  Tip:  'dev' drops you straight into Debian at ~/projects.
============================================================
DONE

}

# Wrapping everything in main() means bash parses the whole script before
# running anything — a truncated `curl | bash` download fails cleanly instead
# of executing half a script. </dev/null stops installers from eating the
# piped-in script text on stdin.
main "$@" </dev/null
