#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

echo "=========================================="
echo "Starting Native Fastfetch Installer for iOS"
echo "=========================================="

# 1. Update/Install necessary build tools via apt if available
if command -v apt &> /dev/null; then
    echo "[*] Updating package list and ensuring dependencies are installed..."
    sudo apt update
    sudo apt install -y git cmake clang make ldid
fi

# 2. Clean up any previous attempts
if [ -d "fastfetch" ]; then
    echo "[*] Removing old fastfetch directory..."
    rm -rf fastfetch
fi

# 3. Clone the official repository
echo "[*] Cloning fastfetch repository..."
git clone https://github.com/fastfetch-cli/fastfetch.git
cd fastfetch

# 4. Create and enter build directory
mkdir build
cd build

# 5. Configure the build for a headless/generic Darwin environment
# This disables desktop extensions that cause compilation failures on iOS
echo "[*] Configuring build options with CMake..."
cmake .. \
    -DENABLE_X11=OFF \
    -DENABLE_WAYLAND=OFF \
    -DENABLE_VULKAN=OFF \
    -DENABLE_DRM=OFF \
    -DENABLE_GIO=OFF \
    -DENABLE_DCONF=OFF \
    -DENABLE_DBUS=OFF \
    -DENABLE_OPENCL=OFF

# 6. Compile the binary
echo "[*] Compiling fastfetch (this may take a minute)..."
make -j$(sysctl -n hw.ncpu)

# 7. Pseudo-sign the binary so iOS doesn't instantly kill it
echo "[*] Code-signing binary with ldid..."
ldid -S fastfetch

# 8. Install to user binaries
echo "[*] Moving fastfetch to /usr/local/bin/..."
sudo mkdir -p /usr/local/bin
sudo mv fastfetch /usr/local/bin/

echo "=========================================="
echo "Successfully installed native fastfetch!"
echo "Type 'fastfetch' in your terminal to run."
echo "=========================================="