#!/bin/bash
set -e

# Check for root
if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root." >&2
    exit 1
fi

# Install required packages
apt update
apt install -y musl-tools wget tar

# 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"

MUSL_CC_URL="https://musl.cc"
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

# x86_64
if [ ! -d "$INSTALL_DIR/x86_64-linux-musl-cross" ]; then
    echo "Downloading x86_64 musl cross toolchain..."
    wget -nc -O "$TMPDIR/x86_64-linux-musl-cross.tgz" $MUSL_CC_URL/x86_64-linux-musl-cross.tgz
    tar -C "$INSTALL_DIR" -xvf "$TMPDIR/x86_64-linux-musl-cross.tgz"
fi

# aarch64
if [ ! -d "$INSTALL_DIR/aarch64-linux-musl-cross" ]; then
    echo "Downloading aarch64 musl cross toolchain..."
    wget -nc -O "$TMPDIR/aarch64-linux-musl-cross.tgz" $MUSL_CC_URL/aarch64-linux-musl-cross.tgz
    tar -C "$INSTALL_DIR" -xvf "$TMPDIR/aarch64-linux-musl-cross.tgz"
fi

# Print instructions for adding to PATH
# cat <<EOF

# To use the musl cross compilers, add the following to your shell:
# export PATH="$INSTALL_DIR/x86_64-linux-musl-cross/bin:$INSTALL_DIR/aarch64-linux-musl-cross/bin:$PATH"

# Or run:
#     export PATH="$INSTALL_DIR/x86_64-linux-musl-cross/bin:$INSTALL_DIR/aarch64-linux-musl-cross/bin:\$PATH"

# EOF

# Clean up
rm -rf "$TMPDIR"

# If run with sudo, add to invoking user's ~/.bashrc
if [ -n "$SUDO_USER" ] && [ "$SUDO_USER" != "root" ]; then
    BASHRC="$USER_HOME/.bashrc"
    EXPORT_LINE="export PATH=\"$INSTALL_DIR/x86_64-linux-musl-cross/bin:$INSTALL_DIR/aarch64-linux-musl-cross/bin:\$PATH\""
    if ! grep -Fxq "$EXPORT_LINE" "$BASHRC"; then
        echo "" >> "$BASHRC"
        echo "# Add musl cross compilers to PATH for bb64" >> "$BASHRC"
        echo "$EXPORT_LINE" >> "$BASHRC"
        echo "Added musl cross compilers to $BASHRC"
    else
        echo "musl cross compiler PATH already present in $BASHRC"
    fi
fi
