#!/usr/bin/env bash
#
# clauded: Wrapper for Claude Code on Termux
# Uses termux-chroot for working /tmp in all child processes
#

set -e

TERMUX_TMP="$PREFIX/tmp"

RED="\033[0;31m"
GREEN="\033[0;32m"
YELLOW="\033[1;33m"
NC="\033[0m"

# Verify termux-chroot
if ! command -v termux-chroot &>/dev/null; then
    echo -e "${RED}Error: termux-chroot not available${NC}"
    echo "Install with: pkg install proot"
    exit 1
fi

# Verify claude
if ! command -v claude &>/dev/null; then
    echo -e "${RED}Error: claude is not installed${NC}"
    exit 1
fi

# Clean orphan Claude temp files (older than 1 day)
find "$TERMUX_TMP" -name "claude-*-cwd" -mtime +1 -delete 2>/dev/null || true

# Check Tailscale connectivity (generic: look for tailscale0 interface)
if ! ip link show tailscale0 &>/dev/null 2>&1; then
    echo -e "${YELLOW}Tailscale not connected${NC} - SSH to remote hosts will fail"
    echo ""
fi

CLAUDE_VER=$(claude --version 2>/dev/null | grep -oE "[0-9]+\.[0-9]+\.[0-9]+" | head -1)
echo -e "${GREEN}Claude Code v$CLAUDE_VER (termux-chroot)${NC}"
echo -e "  /tmp -> /usr/tmp (FHS)"
echo ""

exec termux-chroot claude --dangerously-skip-permissions "$@"
