#!/bin/bash

set -euo pipefail

# SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

ARCHS=(
    "x86_64"
    "aarch64"
)

HOSTARCH=$(uname -m)

SOURCE_DIR=""
BUILD_DIR=""
OUTPUT_DIR=""
EXECUTABLE_NAME=""

# set flags from command line
RELEASE=0
MULTIBUILD=0


function help() {
    echo "Usage: $0 [options]"
    echo "Options:"
    echo "  version   Show version information and exit"
    echo " "
    echo "  <directory>  Build the project using cmake in <directory>"
    echo "     -r, --release   Build release version"
    echo "     -m, --multi     Build for multiple architectures"
}

function version() {
    echo "2025.0531.0942"
}


# ----------------------------------------------------------------------------------------------------------
# BUILD
# ----------------------------------------------------------------------------------------------------------

CMAKE_FILE="CMakeLists.txt"

function get_executable_name() {
    local var_value=""
    local CMAKEFILEPATH="${1:-}"        
    [ -n "${CMAKEFILEPATH:-}" ] || die "No CMake file path given!"
    CMAKEFILEPATH="$CMAKEFILEPATH/${CMAKE_FILE}"
    [ -f "${CMAKEFILEPATH}" ] || die "${CMAKE_FILE} not found in ${CMAKEFILEPATH}"

    echo "Getting executable name from ${CMAKEFILEPATH}"

    while IFS= read -r line; do
        # Look for set(PROJECT_EXE_NAME ipdemo)
        if [[ "$line" =~ set\(PROJECT_EXE_NAME[[:space:]]+([a-zA-Z0-9_-]+)\) ]]; then
            var_value=$(echo "$line" | sed -E 's/.*set\(PROJECT_EXE_NAME[[:space:]]+([a-zA-Z0-9_-]+)\).*/\1/')
        fi
        # Look for add_executable(${PROJECT_EXE_NAME}
        if [[ "$line" =~ add_executable\([[:space:]]*\$\{PROJECT_EXE_NAME\}[[:space:]] ]]; then
            echo "Found executable name: $var_value"
            EXECUTABLE_NAME="$var_value"
        fi
    done < "${CMAKEFILEPATH}"

    [[ -n "$EXECUTABLE_NAME" ]] || die "Executable name not found."
    echo "Executable name: $EXECUTABLE_NAME"
}

function build_arch() {
    local ARCH="$1"
    local CMAKE_DIR="$2"
    
    local BUILD_DIR="${CMAKE_DIR}/build"
    local OUTPUT_DIR="${CMAKE_DIR}/output"

    local PREVDIR="$PWD"
    local JOBS;
    JOBS=$(nproc) # Set JOBS to the number of available CPU cores
    cd "${CMAKE_DIR}" || exit 1

    local ARCH_BUILD_DIR=${BUILD_DIR}/${ARCH}
    mkdir -p "${ARCH_BUILD_DIR}"

    echo "Building for ${ARCH} in ${ARCH_BUILD_DIR}, from ${SOURCE_DIR}"

    if [ ! -f "${HOME}/.musl-cross/${ARCH}-linux-musl-cross/bin/${ARCH}-linux-musl-g++" ]; then
        echo "Musl cross toolchain not found for ${ARCH}."
        exit 1
    fi

    CMAKE_BUILD_TYPE="Release"
    if [ "$RELEASE" -eq 0 ]; then
        CMAKE_BUILD_TYPE="Debug"
    fi

    export CC="${HOME}/.musl-cross/${ARCH}-linux-musl-cross/bin/${ARCH}-linux-musl-gcc"
    export CXX="${HOME}/.musl-cross/${ARCH}-linux-musl-cross/bin/${ARCH}-linux-musl-g++"
    export SYSROOT="${HOME}/.musl-cross/${ARCH}-linux-musl-cross/${ARCH}-linux-musl/sysroot"
    export OPENSSL_ROOT_DIR="${SYSROOT}/usr"
    export CFLAGS="--sysroot=$SYSROOT"
    export CXXFLAGS="--sysroot=$SYSROOT"
    export LDFLAGS="--sysroot=$SYSROOT"
    export MAKEFLAGS="-j${JOBS}"

    cmake -B "${ARCH_BUILD_DIR}" -G Ninja \
        -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}" \
        -DCMAKE_C_COMPILER_LAUNCHER=ccache \
        -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
        -DCMAKE_LINKER=mold \
        -DCMAKE_C_COMPILER_TARGET="${ARCH}-linux-musl" \
        -DCMAKE_CXX_COMPILER_TARGET="${ARCH}-linux-musl" \
        -DCMAKE_C_FLAGS="${CFLAGS}" \
        -DCMAKE_CXX_FLAGS="${CXXFLAGS}" \
        -DCMAKE_FIND_ROOT_PATH="${SYSROOT}" \
        -DCMAKE_SYSROOT="${SYSROOT}"
    cd "${ARCH_BUILD_DIR}" || exit 1
    ninja -k0 -j"${JOBS}"

    if [ "$RELEASE" -eq 1 ]; then
        upx "${ARCH_BUILD_DIR}/${EXECUTABLE_NAME}"
    fi

    if [ ! -d "${OUTPUT_DIR}" ]; then
        mkdir -p "${OUTPUT_DIR}"
    fi
    cp "${ARCH_BUILD_DIR}/${EXECUTABLE_NAME}" "${OUTPUT_DIR}/${EXECUTABLE_NAME}.${ARCH}"
    
    cd "${PREVDIR}" || exit 1
}

function build() {
    echo "Building project in directory $1"
    if [ ! -d "$1" ]; then
        echo "Directory $1 does not exist"
        exit 1
    fi

    local CMAKE_DIR="$1"

    # if have the -m option, then build for multiple architectures
    if [ $MULTIBUILD -eq 1 ]; then
        for arch in "${ARCHS[@]}"; do
            build_arch "$arch" "$CMAKE_DIR"
        done
    else
        build_arch "$HOSTARCH" "$CMAKE_DIR"
    fi
}

function buildspawn() {
    local CMAKE_DIR="${1:-}"
    [ -n "${CMAKE_DIR:-}" ] || die "No CMake Directory given!"
    [ -d "$CMAKE_DIR" ] || die "CMake Directory doesn't exist: $CMAKE_DIR"
    
    # make canonical
    CMAKE_DIR=$(realpath "$CMAKE_DIR")

    get_executable_name "$CMAKE_DIR"

    FLAGS=""
    [ $MULTIBUILD -eq 0 ] || FLAGS="$FLAGS -m"
    [ $RELEASE -eq 0 ] || FLAGS="$FLAGS -r"

    BUILD_VERSION_FILE="$HOME/.config/dropshell-build/version" 
    if [ ! -f "$BUILD_VERSION_FILE" ]; then
        # check if docker is installed
        if ! command -v docker &> /dev/null; then
            echo "Neither dropshell-build nor docker appears to be available. Please install one of them."
            exit 1
        fi
        echo "Using Docker Buildchain."
        TAG="latest"
        if [ -n "${DROPSHELL_BUILD_TAG-}" ]; then
            TAG="$DROPSHELL_BUILD_TAG"
        fi
        echo "Using Docker Buildchain with tag: $TAG"
        

        # Check if we're running in Gitea Actions
        if [ -n "${JOB_CONTAINER_NAME:-}" ] && [ -n "${GITHUB_WORKSPACE:-}" ]; then
            echo "--------------------------------"
            echo "Running in Gitea Actions - using --volumes-from"
            echo "--------------------------------"
            
            echo "ls -la using --volumes-from"
            echo "GITHUB_WORKSPACE:   ${GITHUB_WORKSPACE}"
            echo "CMAKE_DIR:          ${CMAKE_DIR}"
            echo "PWD:                ${PWD}"
            echo "JOB_CONTAINER_NAME: ${JOB_CONTAINER_NAME}"

            docker run --rm \
                --volumes-from="${JOB_CONTAINER_NAME}" \
                "gitea.jde.nz/public/dropshell-build:${TAG}" \
                bash -c "rm -rf /app && \
                    ln -s ${CMAKE_DIR} /app && \
                    dropshell-build $FLAGS /app"
        else
            echo "Running locally"
            docker run --rm \
                -u "$(id -u)":"$(id -g)" \
                -v "$CMAKE_DIR":/app \
                "gitea.jde.nz/public/dropshell-build:${TAG}" \
                bash -c "dropshell-build $FLAGS /app"
        fi
    else    
        echo "Using local native buildchain"
        # shellcheck disable=SC2086
        build $FLAGS $CMAKE_DIR
    fi   
}


# ----------------------------------------------------------------------------------------------------------
# MAIN
# ----------------------------------------------------------------------------------------------------------

function main() {
    while getopts "rm" opt; do
        case $opt in
            r)
                RELEASE=1
                ;;
            m)
                MULTIBUILD=1
                ;;
            *)
                help
                exit 1
                ;;
        esac
    done

    # Shift the processed options out of the argument list
    shift $((OPTIND-1))

    # check we have at least one argument
    if [ $# -eq 0 ]; then
        help
        exit 1
    fi


    # get command argument, now that the flags are set
    CMD="$1"

    if [ -z "$CMD" ]; then
        help
        exit 1
    fi


    case "$CMD" in
        version)
            version
            ;;
        *)
            buildspawn "$1"
            ;;
    esac
}

main "$@"