#!/bin/bash
set -euo pipefail
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

function dothis() {
    local thisthing="$1"
    local dir="$2"

    cmd=""

    [ ! -f "${dir}/${thisthing}.sh" ] || cmd="${dir}/${thisthing}.sh"
    [ ! -f "${dir}/${thisthing}" ] || cmd="${dir}/${thisthing}"

    if [ -z "$cmd" ]; then
        echo "No ${thisthing} script found in $dir"
    else
        echo "Running $cmd"
        "$cmd"
    fi
}

function title() {
    local title="$1"
    local inner_width=59  # Width between the borders (box_width - 2)
    
    # Get the actual display width (handles emojis correctly)
    local title_display_width
    title_display_width=$(echo -n "$title" | wc -L)
    
    # Calculate total padding needed
    local total_padding=$(( inner_width - title_display_width ))
    local left_padding=$(( total_padding / 2 ))
    local right_padding=$(( total_padding - left_padding ))
    
    # Top border
    echo
    printf "╔"
    printf "═%.0s" $(seq 1 $inner_width)
    printf "╗\n"
    
    # Empty line
    printf "║%*s║\n" $inner_width ""
    
    # Title line with padding
    printf "║%*s%s%*s║\n" $left_padding "" "$title" $right_padding ""
    
    # Empty line
    printf "║%*s║\n" $inner_width ""
    
    # Bottom border
    printf "╚"
    printf "═%.0s" $(seq 1 $inner_width)
    printf "╝\n"
    echo
}

function subtitle() {
    local subtitle="$1"
    echo " "
    echo "--------------------------------"
    echo "$subtitle"
    echo " "
}

function buildtestpublish() {
    local dir="$1"

    TOOLNAME=$(basename "$dir")
    TOOLNAME=$(echo "$TOOLNAME" | tr '[:lower:]' '[:upper:]')
    title "🔧 $TOOLNAME 🔧"

    export PROJECT="$TOOLNAME"

    cd "$dir"

    subtitle "🔨 BUILDING $TOOLNAME 🔨"
    dothis build "$dir"

    subtitle "🔍 TESTING $TOOLNAME 🔍"
    dothis test "$dir"

    subtitle "📦 PUBLISHING $TOOLNAME 📦"
    dothis publish "$dir"

    echo "Done"
}

function buildtestpublish_all() {
    PREVIOUS_DIR=$(pwd)

    # find all subdirectories in the current directory that don't begin with a dot
    find "$SCRIPT_DIR" -maxdepth 1 -type d \
        -not -name ".*" \
        -not -path "$SCRIPT_DIR" \
        -print0 | while IFS= read -r -d '' dir; \
        do

        buildtestpublish "${dir}"
    done

    cd "$PREVIOUS_DIR"
}

title "🔨 BUILDING ALL TOOLS 🔨"

getpkg/build.sh
export GETPKG="${SCRIPT_DIR}/getpkg/output/getpkg"
[ -f "$GETPKG" ] || die "Build failed."

buildtestpublish_all

title "🚀 Deployment Complete! 🚀"