#!/bin/bash
# Termux Bootstrap for SaltyBot Phone Node

set -e
echo "=== SaltyBot Phone Node Bootstrap ==="
apt update -y && apt upgrade -y
apt install -y python3 python3-pip git curl wget vim openssh termux-api

pip install -q --upgrade pip setuptools wheel
pip install -q colcon-common-extensions rclpy sensor_msgs geometry_msgs cv_bridge pillow opencv-python ollama

if [ ! -d "$HOME/.local/llama.cpp" ]; then
    git clone https://github.com/ggerganov/llama.cpp $HOME/.local/llama.cpp
    cd $HOME/.local/llama.cpp && make
fi

mkdir -p ~/.cache/openclaw ~/saltybot_workspace

mkdir -p ~/.ssh
if [ ! -f ~/.ssh/id_rsa ]; then
    ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -N ""
fi

mkdir -p ~/.termux/boot
cat > ~/.termux/boot/saltybot-phone-start.sh << 'EOF'
#!/bin/bash
export PATH="$HOME/.local/bin:$PATH"
cd ~/saltybot_workspace
source install/setup.bash
ros2 launch saltybot_phone phone_bringup.py &
echo "SaltyBot phone node started at $(date)" >> ~/phone-node.log
EOF
chmod +x ~/.termux/boot/saltybot-phone-start.sh

mkdir -p ~/.config/termux
cat > ~/.config/termux/power-monitor.sh << 'EOF'
#!/bin/bash
while true; do
    BATTERY=$(termux-battery-status | grep -o 'percentage":[0-9]*' | cut -d: -f2)
    if [ "$BATTERY" -lt "20" ]; then
        echo "Battery low ($BATTERY%)" >> ~/power-monitor.log
    fi
    sleep 60
done
EOF
chmod +x ~/.config/termux/power-monitor.sh

echo "=== Bootstrap Complete ==="
echo "Next: Download saltybot_phone to ~/saltybot_workspace/src/ && colcon build"
