#!/data/data/com.termux/files/usr/bin/bash
# ═══════════════════════════════════════════════════════════════════
# Alfred Linux Mobile Installer
# Version: 1.0.0 — April 6, 2026
# Compatible: Samsung Galaxy S26 Ultra, Pixel, any Android 12+
# Method: Termux + proot-distro (NO ROOT REQUIRED)
# ═══════════════════════════════════════════════════════════════════
#
# PREREQUISITES:
#   1. Install Termux from F-Droid (NOT Google Play — that version is outdated)
#      https://f-droid.org/en/packages/com.termux/
#   2. Open Termux and run:
#      curl -fsSL https://alfredlinux.com/downloads/install-alfred-mobile.sh | bash
#
# WHAT THIS DOES:
#   - Installs proot-distro in Termux
#   - Creates a Debian Bookworm environment (same base as Alfred Linux desktop)
#   - Installs Alfred IDE (code-server) accessible via browser
#   - Installs Alfred Voice (Kokoro TTS)
#   - Installs Alfred Search (Meilisearch)
#   - Creates 'alfred' launcher command
#
# STORAGE: ~4 GB after full install
# ═══════════════════════════════════════════════════════════════════

set -e

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

banner() {
    echo ""
    echo -e "${AMBER}${BOLD}"
    echo "  ╔═══════════════════════════════════════╗"
    echo "  ║         ALFRED LINUX MOBILE           ║"
    echo "  ║     The AI-Native OS — Everywhere     ║"
    echo "  ╚═══════════════════════════════════════╝"
    echo -e "${NC}"
    echo -e "  ${CYAN}Version 1.0.0 · April 2026 · Debian Bookworm${NC}"
    echo ""
}

step() {
    echo -e "\n${GREEN}${BOLD}[$(date +%H:%M:%S)] ▸ $1${NC}"
}

warn() {
    echo -e "${AMBER}  ⚠ $1${NC}"
}

fail() {
    echo -e "${RED}${BOLD}  ✗ $1${NC}"
    exit 1
}

ok() {
    echo -e "${GREEN}  ✓ $1${NC}"
}

# ── Preflight ──────────────────────────────────────────────────────
banner

# Verify we're in Termux
if [[ ! -d /data/data/com.termux ]]; then
    fail "This script must be run inside Termux on Android."
fi

step "Checking Android environment..."
ARCH=$(uname -m)
echo "  Architecture: $ARCH"
echo "  Android API: $(getprop ro.build.version.sdk 2>/dev/null || echo 'unknown')"
echo "  Device: $(getprop ro.product.model 2>/dev/null || echo 'unknown')"
echo "  Storage free: $(df -h /data | tail -1 | awk '{print $4}')"

if [[ "$ARCH" != "aarch64" && "$ARCH" != "arm64" && "$ARCH" != "x86_64" ]]; then
    fail "Unsupported architecture: $ARCH. Need arm64 or x86_64."
fi

# Check available storage (need at least 4GB)
FREE_MB=$(df -m /data | tail -1 | awk '{print $4}')
if [[ "$FREE_MB" -lt 3000 ]]; then
    warn "Low storage: ${FREE_MB}MB free. Alfred needs ~4GB. Continuing anyway..."
fi

# ── Phase 1: Update Termux ────────────────────────────────────────
step "Updating Termux packages..."
pkg update -y 2>&1 | tail -3
pkg upgrade -y 2>&1 | tail -3
ok "Termux updated"

# ── Phase 2: Install proot-distro ─────────────────────────────────
step "Installing proot-distro..."
pkg install -y proot-distro pulseaudio 2>&1 | tail -3
ok "proot-distro installed"

# ── Phase 3: Install Debian Bookworm ──────────────────────────────
step "Installing Debian Bookworm (Alfred Linux base)..."
if proot-distro list | grep -q "debian.*installed"; then
    warn "Debian already installed — using existing installation"
else
    proot-distro install debian 2>&1 | tail -5
fi
ok "Debian Bookworm ready"

# ── Phase 4: Alfred Layer Installation ────────────────────────────
step "Installing Alfred Linux components inside Debian..."

proot-distro login debian -- bash -c '
set -e

echo "[Alfred] Updating base system..."
apt-get update -qq
apt-get upgrade -y -qq

echo "[Alfred] Installing core packages..."
apt-get install -y -qq \
    curl wget git sudo nano htop neofetch \
    python3 python3-pip python3-venv \
    nodejs npm \
    build-essential \
    ca-certificates \
    locales \
    2>&1 | tail -5

# Set locale
sed -i "s/# en_US.UTF-8/en_US.UTF-8/" /etc/locale.gen
locale-gen en_US.UTF-8 2>/dev/null || true

# ── Alfred IDE (code-server) ──
echo "[Alfred] Installing Alfred IDE (code-server)..."
if ! command -v code-server &>/dev/null; then
    curl -fsSL https://code-server.dev/install.sh | sh -s -- --method=standalone 2>&1 | tail -3
fi
echo "[Alfred IDE] Installed: $(code-server --version 2>/dev/null | head -1)"

# Configure code-server for mobile
mkdir -p ~/.config/code-server
cat > ~/.config/code-server/config.yaml << IDECONF
bind-addr: 0.0.0.0:8080
auth: none
cert: false
app-name: Alfred IDE Mobile
IDECONF

# ── Alfred Search (Meilisearch) ──
echo "[Alfred] Installing Alfred Search (Meilisearch)..."
if ! command -v meilisearch &>/dev/null; then
    curl -fsSL https://install.meilisearch.com | sh 2>&1 | tail -3
    mv ./meilisearch /usr/local/bin/ 2>/dev/null || true
fi

# ── Alfred Voice (Kokoro TTS) ──
echo "[Alfred] Installing Alfred Voice (Kokoro TTS)..."
python3 -m venv /opt/alfred-voice 2>/dev/null || true
/opt/alfred-voice/bin/pip install --quiet kokoro 2>&1 | tail -3 || echo "[Alfred Voice] Note: Full voice engine requires more resources. Basic install done."

# ── Alfred Branding ──
echo "[Alfred] Applying Alfred Linux branding..."
mkdir -p /etc/alfred

cat > /etc/alfred/release << RELEASE
ALFRED_LINUX_VERSION="2.0-mobile"
ALFRED_LINUX_CODENAME="Sovereign"
ALFRED_LINUX_BUILD="rc3-mobile"
ALFRED_LINUX_DATE="2026-04-06"
ALFRED_LINUX_BASE="Debian Bookworm"
ALFRED_LINUX_EDITION="Mobile"
RELEASE

# Custom MOTD
cat > /etc/motd << MOTD

  ╔═══════════════════════════════════════╗
  ║      ALFRED LINUX 2.0 — MOBILE       ║
  ║   The AI-Native OS — In Your Pocket   ║
  ╚═══════════════════════════════════════╝

  Alfred IDE:    code-server (port 8080)
  Alfred Search: meilisearch (port 7700)
  Alfred Voice:  kokoro-tts

  Commands:
    alfred-ide     → Launch Alfred IDE in browser
    alfred-search  → Start Meilisearch
    alfred-info    → System info

MOTD

# ── Custom neofetch config ──
mkdir -p ~/.config/neofetch
cat > ~/.config/neofetch/config.conf << NEOFETCH
print_info() {
    info title
    info underline
    info "OS" distro
    info "Host" model
    info "Kernel" kernel
    info "Shell" shell
    info "Packages" packages
    info "Memory" memory
    info "Disk" disk
    info "Alfred" local_ip
}
NEOFETCH

echo ""
echo "[Alfred] ✓ All components installed successfully!"
echo ""
'

ok "Alfred Linux components installed in Debian"

# ── Phase 5: Create Launcher Commands ─────────────────────────────
step "Creating launcher commands..."

# Main alfred command
cat > "$PREFIX/bin/alfred" << 'LAUNCHER'
#!/data/data/com.termux/files/usr/bin/bash
echo ""
echo "  ╔═══════════════════════════════════════╗"
echo "  ║      ALFRED LINUX 2.0 — MOBILE       ║"
echo "  ╚═══════════════════════════════════════╝"
echo ""
proot-distro login debian
LAUNCHER
chmod +x "$PREFIX/bin/alfred"

# Alfred IDE launcher
cat > "$PREFIX/bin/alfred-ide" << 'IDELAUNCHER'
#!/data/data/com.termux/files/usr/bin/bash
echo ""
echo "  Starting Alfred IDE on port 8080..."
echo "  Open your browser to: http://localhost:8080"
echo ""
proot-distro login debian -- bash -c 'code-server --bind-addr 0.0.0.0:8080 2>&1' &
sleep 2
am start -a android.intent.action.VIEW -d "http://localhost:8080" 2>/dev/null || echo "  Open http://localhost:8080 in your browser"
echo ""
echo "  Alfred IDE is running. Press Ctrl+C to stop."
wait
IDELAUNCHER
chmod +x "$PREFIX/bin/alfred-ide"

# Alfred info command
cat > "$PREFIX/bin/alfred-info" << 'INFOLAUNCHER'
#!/data/data/com.termux/files/usr/bin/bash
proot-distro login debian -- bash -c '
cat /etc/alfred/release 2>/dev/null
echo ""
echo "Device: $(uname -m)"
echo "Kernel: $(uname -r)"
echo "Debian: $(cat /etc/debian_version)"
echo ""
echo "Installed Components:"
command -v code-server &>/dev/null && echo "  ✓ Alfred IDE (code-server $(code-server --version 2>/dev/null | head -1))"
command -v meilisearch &>/dev/null && echo "  ✓ Alfred Search (Meilisearch)"
[[ -d /opt/alfred-voice ]] && echo "  ✓ Alfred Voice (Kokoro TTS)"
echo ""
'
INFOLAUNCHER
chmod +x "$PREFIX/bin/alfred-info"

ok "Launcher commands created"

# ── Phase 6: Termux Shortcuts (optional) ──────────────────────────
step "Creating Termux widget shortcuts..."
mkdir -p ~/.shortcuts
echo '#!/data/data/com.termux/files/usr/bin/bash
alfred-ide' > ~/.shortcuts/Alfred-IDE
chmod +x ~/.shortcuts/Alfred-IDE

echo '#!/data/data/com.termux/files/usr/bin/bash
alfred' > ~/.shortcuts/Alfred-Shell
chmod +x ~/.shortcuts/Alfred-Shell

ok "Shortcuts created (install Termux:Widget for home screen access)"

# ── Done ──────────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}${BOLD}"
echo "  ╔═══════════════════════════════════════╗"
echo "  ║     INSTALLATION COMPLETE! ✓          ║"
echo "  ╚═══════════════════════════════════════╝"
echo -e "${NC}"
echo -e "  ${BOLD}Quick Start:${NC}"
echo ""
echo -e "    ${CYAN}alfred${NC}        → Enter Alfred Linux shell"
echo -e "    ${CYAN}alfred-ide${NC}    → Launch Alfred IDE in browser"
echo -e "    ${CYAN}alfred-info${NC}   → Show system info"
echo ""
echo -e "  ${BOLD}Samsung DeX:${NC}"
echo -e "    Connect to monitor/TV, launch alfred-ide,"
echo -e "    and you have a full desktop IDE experience."
echo ""
echo -e "  ${BOLD}What you have:${NC}"
echo -e "    • Full Debian Bookworm Linux environment"
echo -e "    • Alfred IDE (VS Code in browser)"
echo -e "    • Alfred Search (Meilisearch)"
echo -e "    • Alfred Voice (Kokoro TTS)"
echo -e "    • Python 3, Node.js, Git, and build tools"
echo ""
echo -e "  ${AMBER}Alfred Linux 2.0 Mobile — Your phone is now a sovereign computer.${NC}"
echo ""
