#!/data/data/com.termux/files/usr/bin/bash
#
# Changemaker SMS Server — One-Command Phone Setup
#
# Usage:
#   bash setup.sh YOUR_API_KEY
#
# This script:
#   1. Installs required packages (python, termux-api, flask)
#   2. Saves the API key to ~/.bashrc
#   3. Requests SMS & Contacts permissions
#   4. Sets up Termux:Boot auto-start (if installed)
#   5. Starts the SMS server
#

set -e

# --- Colors ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

step() { echo -e "\n${CYAN}[$1/6]${NC} ${BOLD}$2${NC}"; }
ok()   { echo -e "  ${GREEN}✓${NC} $1"; }
warn() { echo -e "  ${YELLOW}!${NC} $1"; }
fail() { echo -e "  ${RED}✗${NC} $1"; exit 1; }

# --- Banner ---
echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo -e "${BOLD}  Changemaker SMS Server — Phone Setup${NC}"
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"

# --- Validate API key ---
API_KEY="$1"
if [ -z "$API_KEY" ]; then
  echo ""
  echo -e "${RED}Usage: bash setup.sh YOUR_API_KEY${NC}"
  echo ""
  echo "Get the API key from the admin dashboard:"
  echo "  SMS Setup → Step 3 → Generate API Key → Copy"
  exit 1
fi

if [ ${#API_KEY} -lt 32 ]; then
  fail "API key looks too short (expected 64 hex characters). Check you copied the full key."
fi

# --- Step 1: Install packages ---
step 1 "Installing packages"

pkg update -y 2>/dev/null || true
pkg install -y python git termux-api openssh 2>/dev/null

if ! command -v python &>/dev/null; then
  fail "Python failed to install"
fi
ok "python, git, termux-api, openssh installed"

if ! pip show flask &>/dev/null; then
  pip install flask 2>/dev/null
fi
ok "Flask installed"

# --- Step 2: Save API key ---
step 2 "Saving API key"

export SMS_API_SECRET="$API_KEY"

SHELL_RC="$HOME/.bashrc"
[ -f "$HOME/.zshrc" ] && ! [ -f "$HOME/.bashrc" ] && SHELL_RC="$HOME/.zshrc"

# Remove any existing SMS_API_SECRET lines
if grep -q "SMS_API_SECRET" "$SHELL_RC" 2>/dev/null; then
  sed -i '/SMS_API_SECRET/d' "$SHELL_RC"
  warn "Replaced existing API key"
fi

echo "" >> "$SHELL_RC"
echo "# Changemaker SMS Server" >> "$SHELL_RC"
echo "export SMS_API_SECRET=\"$API_KEY\"" >> "$SHELL_RC"
ok "Key saved to $SHELL_RC"
ok "Key active in current session"

# --- Step 3: Grant permissions ---
step 3 "Requesting Android permissions"
echo -e "  ${YELLOW}Tap 'Allow' if Android shows permission prompts${NC}"

# These trigger permission dialogs; capture output to suppress noise
termux-sms-list -l 1 >/dev/null 2>&1 && ok "SMS permission granted" || warn "SMS permission — check Android Settings → Termux:API → Permissions"
termux-contact-list >/dev/null 2>&1 && ok "Contacts permission granted" || warn "Contacts permission — check Android Settings → Termux:API → Permissions"
termux-battery-status >/dev/null 2>&1 && ok "Battery status accessible" || true

# --- Step 4: Create logs directory ---
step 4 "Setting up directories"

mkdir -p ~/logs
ok "~/logs created"

# --- Step 5: Install service supervisor ---
step 5 "Installing termux-services (runit)"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

pkg install -y termux-services 2>/dev/null
ok "termux-services (runit) installed"

# Source runit helpers
source "$PREFIX/etc/profile.d/start-services.sh" 2>/dev/null || true

# Make run scripts executable
chmod +x "$SCRIPT_DIR/services/sms-api/run" 2>/dev/null || true
chmod +x "$SCRIPT_DIR/services/sms-api/log/run" 2>/dev/null || true
chmod +x "$SCRIPT_DIR/services/sshd/run" 2>/dev/null || true

# Register services with runit
mkdir -p "$PREFIX/var/service"
rm -f "$PREFIX/var/service/sms-api" 2>/dev/null
rm -f "$PREFIX/var/service/sshd-custom" 2>/dev/null
ln -s "$SCRIPT_DIR/services/sms-api" "$PREFIX/var/service/sms-api"
ln -s "$SCRIPT_DIR/services/sshd" "$PREFIX/var/service/sshd-custom"
ok "sms-api and sshd-custom services registered"

# Set up Termux:Boot auto-start
if dpkg -l 2>/dev/null | grep -q termux-boot 2>/dev/null || [ -d "$HOME/.termux/boot" ]; then
  mkdir -p ~/.termux/boot
  cp "$SCRIPT_DIR/termux-boot-start.sh" ~/.termux/boot/start-sms-server 2>/dev/null || {
    cat > ~/.termux/boot/start-sms-server << 'BOOT'
#!/data/data/com.termux/files/usr/bin/bash
termux-wake-lock
[ -f "$HOME/.bashrc" ] && . "$HOME/.bashrc"
. "$PREFIX/etc/profile.d/start-services.sh" 2>/dev/null || true
BOOT
  }
  chmod +x ~/.termux/boot/start-sms-server
  ok "Boot script installed (auto-start on reboot)"
else
  warn "Termux:Boot not detected — install from F-Droid for auto-start on reboot"
fi

# --- Step 6: Start the server ---
step 6 "Starting SMS server"

# Kill any old watchdog/standalone instances
pkill -f sms-watchdog.sh 2>/dev/null || true
pkill -f termux-sms-api-server.py 2>/dev/null || true
sleep 1

# Acquire wake lock
termux-wake-lock 2>/dev/null || true

# runit auto-starts services — just wait for it
sleep 3

# Check if it's running
if curl -s --max-time 5 http://127.0.0.1:5001/health >/dev/null 2>&1; then
  ok "Server is running via runit!"
  sv status sms-api 2>/dev/null || true
else
  warn "Server starting up... check: sv status sms-api"
fi

# --- Summary ---
echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo -e "${GREEN}${BOLD}  Setup complete!${NC}"
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo ""

# Get device IP
DEVICE_IP=$(ip -4 addr show 2>/dev/null | grep -oP '(?<=inet\s)(?!127\.)\d+\.\d+\.\d+\.\d+' | head -1)
if [ -n "$DEVICE_IP" ]; then
  echo -e "  Phone URL:  ${BOLD}http://${DEVICE_IP}:5001${NC}"
fi
echo -e "  Health:     ${BOLD}http://127.0.0.1:5001/health${NC}"
echo -e "  Status:     ${BOLD}sv status sms-api${NC}"
echo -e "  Restart:    ${BOLD}sv restart sms-api${NC}"
echo -e "  Logs:       ${BOLD}tail -f ~/logs/sms-api.log${NC}"
echo ""
echo -e "  ${YELLOW}Next:${NC} Go back to the admin dashboard SMS Setup wizard"
echo -e "  and enter this phone's URL in Step 2 (Connect)."
echo ""

# Show Tailscale IP if available
TS_IP=$(ip -4 addr show tailscale0 2>/dev/null | grep -oP '(?<=inet\s)\d+\.\d+\.\d+\.\d+' || true)
if [ -n "$TS_IP" ]; then
  echo -e "  ${GREEN}Tailscale IP: ${BOLD}http://${TS_IP}:5001${NC} (recommended)"
  echo ""
fi
