#!/bin/bash

# ============================================
# Script to Install Headless Blender on Alpine
# within proot-distro on Termux
# ============================================

# Exit immediately if a command exits with a non-zero status
set -e

# Function to display messages
echo_error() {
    echo -e "\e[31mERROR: $1\e[0m"
}

echo_info() {
    echo -e "\e[32mINFO: $1\e[0m"
}

# Step 1: Update Termux Packages
echo_info "Updating Termux packages..."
pkg update && pkg upgrade -y

# Install proot-distro if not installed
if ! command -v proot-distro &> /dev/null; then
    echo_info "Installing proot-distro..."
    pkg install proot-distro -y
else
    echo_info "proot-distro is already installed."
fi

# Step 2: Install Alpine Linux via proot-distro
DISTRO="alpine"

if ! proot-distro list | grep -q "^${DISTRO}"; then
    echo_info "Installing Alpine Linux..."
    proot-distro install alpine
else
    echo_info "Alpine is already installed."
fi

# Step 3: Configure and Update Alpine
echo_info "Configuring Alpine Linux environment..."

proot-distro login alpine -- /bin/sh -c "
    # Update apk repositories
    apk update && 
    apk upgrade && 

    # Install necessary packages
    apk add --no-cache bash wget tar libstdc++ libgcc libx11 libxext libxi libxrandr libxinerama libxxf86vm libgl1-mesa-glx mesa-dri-gallium libpng libjpeg-turbo xvfb

    # Install additional dependencies for Blender (if any)
    # Note: You might need to adjust dependencies based on Blender's requirements
"

echo_info "Alpine Linux is updated and necessary dependencies are installed."

# Step 4: Download and Setup Blender
# Define Blender version and architecture
BLENDER_VERSION="3.6.0"
ARCH="aarch64"  # Change to "x86_64" if applicable

# Construct download URL (Modify if Blender releases ARM builds)
BLENDER_URL="https://download.blender.org/release/Blender${BLENDER_VERSION}/blender-${BLENDER_VERSION}-linux-${ARCH}.tar.xz"

# Check if Blender build exists for the architecture
echo_info "Checking Blender download URL: $BLENDER_URL"

HTTP_STATUS=$(curl -o /dev/null -s -w "%{http_code}\n" "$BLENDER_URL")

if [ "$HTTP_STATUS" -ne 200 ]; then
    echo_error "Blender build for architecture '${ARCH}' not found."
    echo_info "You may need to compile Blender from source or find a compatible build."
    exit 1
fi

# Proceed to download and extract Blender
proot-distro login alpine -- /bin/sh -c "
    mkdir -p /opt/blender &&

    echo_info() {
        echo -e \"\e[32mINFO: \$1\e[0m\"
    }

    echo_info \"Downloading Blender ${BLENDER_VERSION}...\"
    wget ${BLENDER_URL} -O /tmp/blender.tar.xz &&

    echo_info \"Extracting Blender...\"
    tar -xf /tmp/blender.tar.xz -C /opt/blender --strip-components=1 &&

    echo_info \"Creating symbolic link for Blender...\"
    ln -sf /opt/blender/blender /usr/local/bin/blender &&

    echo_info \"Cleaning up installation files...\"
    rm /tmp/blender.tar.xz
"

# Step 5: Verify Blender Installation
echo_info "Verifying Blender installation..."

proot-distro login alpine -- /bin/sh -c "
    blender --version
"

echo_info "Headless Blender installation completed successfully!"

# Optional: Usage Example
echo_info "You can run Blender in headless mode using the following command:"
echo "proot-distro login alpine -- blender --background --render-output //render/frame_#### --render-anim //path/to/your/file.blend"
(venv)  daddy@localhost  ~  bash ./bb.sh
INFO: Updating Termux packages...
No mirror or mirror group selected. You might want to select one by running 'termux-change-repo'
Checking availability of current mirror:
[*] https://packages-cf.termux.dev/apt/termux-main: ok
Get:1 https://packages-cf.termux.dev/apt/termux-main stable InRelease [14.0 kB]
Get:2 https://packages-cf.termux.dev/apt/termux-main stable/main aarch64 Packages [523 kB]
Fetched 537 kB in 2s (312 kB/s)
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
All packages are up to date.
No mirror or mirror group selected. You might want to select one by running 'termux-change-repo'
Checking availability of current mirror:
[*] https://packages-cf.termux.dev/apt/termux-main: ok
Hit:1 https://packages-cf.termux.dev/apt/termux-main stable InRelease
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
All packages are up to date.
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
INFO: proot-distro is already installed.

Error: proot-distro should not be executed under PRoot.

INFO: Installing Alpine Linux...

Error: proot-distro should not be executed under PRoot.

(venv)  ✘ daddy@localhost  ~ 