#!/bin/bash
# This script is used to build a Hugo site and prepare it for deployment.
GITHUB_WORKSPACE=${GITHUB_WORKSPACE:-$(pwd)}

command -v hugo >/dev/null 2>&1 || { echo >&2 "Hugo is not installed. Please install Hugo to use this script."; exit 1; }

mkdir -p "$GITHUB_WORKSPACE/websites/releases"

for dir in $(find "$GITHUB_WORKSPACE/websites" -maxdepth 1 -type d | grep -vE '^\.$'); do
    if [ "$dir" == "$GITHUB_WORKSPACE/websites" ]; then
        echo "Skipping $dir"
        continue
    fi
    if [ "$dir" == "$GITHUB_WORKSPACE/websites/themes" ]; then
        echo "Skipping $dir"
        continue
    fi
    if [ "$dir" == "$GITHUB_WORKSPACE/websites/releases" ]; then
        echo "Skipping $dir"
        continue
    fi
    if [ -d "$dir" ]; then
        echo "Building Hugo site in $dir"
        cd "$dir" || exit 1
        hugo --minify --themesDir $GITHUB_WORKSPACE/websites/themes --destination $GITHUB_WORKSPACE/websites/releases/$(basename "$dir") --baseURL "https://$(basename "$dir").example.com" 
        if [ $? -ne 0 ]; then
            echo "Hugo build failed in $dir"
            exit 1
        fi
        echo "Hugo site built successfully in $dir"
    else
        echo "$dir is not a directory, skipping..."
    fi
done