#!/bin/bash

# Exit on error
set -e

# DIRECTORIES
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
EXE_DIR="${SCRIPT_DIR}/output"
PROJECTNAME="simple_object_storage"

rm -f ${EXE_DIR}/*

# FUNCTIONS
function title() {
    echo "----------------------------------------"
    # Center the text
    local text="$1"
    local line_length=40
    local text_length=${#text}
    local padding=$(( (line_length - text_length) / 2 ))
    printf "%*s%s%*s\n" $padding "" "$text" $padding ""
    echo "----------------------------------------"
}   

function die() {
    echo " "
    title "$1"
    echo " "
    exit 1
}

function build_amd64() {
# Build for amd64 (musl)
echo "Building for amd64 (musl)..."
cmake -B build_amd64 -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_C_COMPILER=x86_64-linux-musl-gcc \
  -DCMAKE_CXX_COMPILER=x86_64-linux-musl-g++ \
  -DCMAKE_EXE_LINKER_FLAGS="-static" \
  -DCMAKE_CXX_FLAGS="-march=x86-64" .
cmake --build build_amd64 --target simple_object_storage --config Release -j"$JOBS"
mkdir -p ${EXE_DIR}
cp build_amd64/${PROJECTNAME} ${EXE_DIR}/${PROJECTNAME}.amd64
}

function build_arm64() {
# Build for arm64 (musl)
echo "Building for arm64 (musl)..."
cmake -B build_arm64 -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_C_COMPILER=aarch64-linux-musl-gcc \
  -DCMAKE_CXX_COMPILER=aarch64-linux-musl-g++ \
  -DCMAKE_EXE_LINKER_FLAGS="-static" \
  -DCMAKE_CXX_FLAGS="-march=armv8-a" \
  -DCMAKE_SYSTEM_PROCESSOR=aarch64 .
cmake --build build_arm64 --target simple_object_storage --config Release -j"$JOBS"
mkdir -p ${EXE_DIR}
cp build_arm64/${PROJECTNAME} ${EXE_DIR}/${PROJECTNAME}.arm64
}

#--------------------------------
# MAIN
#--------------------------------
cd $SCRIPT_DIR

mkdir -p ${EXE_DIR}

BUILDSTR="amd64"

if [ ! -z "$1" ]; then
    BUILDSTR="$1"
fi

if [ "$BUILDSTR" = "all" ] || [ "$BUILDSTR" = "arm64" ]; then
    title "Building linux-arm64 executable"
    build_arm64 || die "Failed to build linux-arm64 executable"
    echo "arm64 executable: ./simple_object_storage-linux-arm64" 
fi

if [ "$BUILDSTR" = "all" ] || [ "$BUILDSTR" = "amd64" ]; then
    title "Building linux-x86_64 executable"
    build_amd64 || die "Failed to build linux-x86_64 executable"
    echo "amd64 executable: ./simple_object_storage-linux-amd64" 
fi

echo "Build completed successfully!"

