#!/bin/bash

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to print status messages
print_status() {
    echo -e "${GREEN}[*] $1${NC}"
}

print_error() {
    echo -e "${RED}[!] $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}[!] $1${NC}"
}

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    print_error "Please run this script as root (use sudo)"
    exit 1
fi

# Detect distribution
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
else
    print_error "Could not detect distribution"
    exit 1
fi

print_status "Detected OS: $OS $VER"


#----------------------------------------------------------------------------------------------------------
# INSTALL PREREQUISITE PACKAGES
#----------------------------------------------------------------------------------------------------------

# Define packages based on distribution
case $OS in
    "Ubuntu"|"Debian GNU/Linux")
        # Common packages for both Ubuntu and Debian
        PACKAGES="bash cmake make g++ devscripts debhelper build-essential upx musl-tools wget tar ccache ninja-build"
        INSTALLCMD="apt-get install -y"
        UPDATECMD="apt-get update"
        ;;
    "Alpine Linux")
        PACKAGES="bash build-base cmake git nlohmann-json wget tar curl ninja mold nodejs npm"
        INSTALLCMD="apk add --no-cache"
        UPDATECMD="apk update"
        ;;
    *)
        print_error "Unsupported distribution: $OS"
        exit 1
        ;;
esac

# Function to check if a package is installed
is_package_installed() {
    if [ "$OS" = "Alpine Linux" ]; then
        # Use apk info <pkg> and check exit status
        apk info "$1" >/dev/null 2>&1
        return $?
    else
        dpkg -l "$1" 2>/dev/null | grep -q "^ii"
    fi
}

UPDATED=false

# Install missing packages
print_status "Checking and installing required packages..."
for pkg in $PACKAGES; do
    if ! is_package_installed "$pkg"; then
        if [ "$UPDATED" = false ]; then
            print_status "Updating package lists..."
            $UPDATECMD
            UPDATED=true
        fi

        print_status "Installing $pkg..."
        $INSTALLCMD "$pkg"
        if [ $? -ne 0 ]; then
            print_error "Failed to install $pkg"
            exit 1
        fi
    else
        print_status "$pkg is already installed"
    fi
done

# ----------------------------------------------------------------------------------------------------------
# MUSL CROSS COMPILERS
# ----------------------------------------------------------------------------------------------------------

# Set install directory
if [ -n "$SUDO_USER" ] && [ "$SUDO_USER" != "root" ]; then
    USER_HOME=$(eval echo "~$SUDO_USER")
else
    USER_HOME="$HOME"
fi
INSTALL_DIR="$USER_HOME/.musl-cross"
mkdir -p "$INSTALL_DIR"

TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

function install_musl_cross() {
    local TOOLCHAIN="$1"
    local MUSL_CC_URL="https://musl.cc"
    if [ ! -d "$INSTALL_DIR/$TOOLCHAIN" ]; then
        echo "Downloading $TOOLCHAIN musl cross toolchain..."
        wget -nc -O "$TMPDIR/$TOOLCHAIN.tgz" "$MUSL_CC_URL/$TOOLCHAIN.tgz"
        tar -C "$INSTALL_DIR" -xvf "$TMPDIR/$TOOLCHAIN.tgz"
    fi
}

function check_path() {
    if [ -n "$SUDO_USER" ] && [ "$SUDO_USER" != "root" ]; then
        local BASHRC="$USER_HOME/.bashrc"
        local TOOLCHAIN="$1"
        local MUSL_PATH="$INSTALL_DIR/$TOOLCHAIN/bin"
        if ! echo "$PATH" | grep -q "$MUSL_PATH"; then
            echo "Adding $MUSL_PATH to PATH in $BASHRC"
            PATH_LINE="export PATH=\"$MUSL_PATH:\$PATH\""
            if ! grep -Fxq "$PATH_LINE" "$BASHRC"; then
                echo "" >> "$BASHRC"
                echo "# Add musl cross compilers to PATH for dropshell" >> "$BASHRC"
                echo "$PATH_LINE" >> "$BASHRC"
                echo "Added musl cross compilers to $BASHRC"
                echo "You should run 'source ~/.bashrc' to update your PATH"
            else
                echo "You should run 'source ~/.bashrc' to update your PATH"
            fi
        fi
    fi
}


TOOLCHAIN_LIST=(
    "aarch64-linux-musl-cross"
    "x86_64-linux-musl-cross"
    "x86_64-linux-musl-native"
)

for TOOLCHAIN in "${TOOLCHAIN_LIST[@]}"; do
    install_musl_cross "$TOOLCHAIN"
    check_path "$TOOLCHAIN"
done

# Clean up
rm -rf "$TMPDIR"

# ----------------------------------------------------------------------------------------------------------
# COMPLETE
# ----------------------------------------------------------------------------------------------------------

print_status "All dependencies installed successfully!"
print_status "You can now run ./build.sh to build the project"