#!/usr/bin/env bash
#
# publish.sh — Linux/macOS counterpart of publish.ps1.
#
# Publishes the Mbproxy binary in two flavours for the requested runtime under
# <repo>/publish-out/:
#
#   self-contained/        ~100 MB — bundles the .NET 10 + ASP.NET Core runtime;
#                                    no .NET install needed on the target.
#   framework-dependent/   ~1.6 MB — requires the .NET 10 + ASP.NET Core runtime
#                                    preinstalled on the target.
#
# Both builds use the Release configuration and inherit the publish settings in
# src/Mbproxy/Mbproxy.csproj (those settings are gated on an explicit RID, which
# is supplied here). The framework-dependent build overrides SelfContained=false.
#
# Usage:
#   ./publish.sh [-r RID] [-o OUTPUT_DIR] [--clean]
#
#   -r RID          .NET runtime identifier (default: linux-x64)
#   -o OUTPUT_DIR   root output directory (default: <repo>/publish-out)
#   --clean         delete OUTPUT_DIR before publishing
#
# Examples:
#   ./publish.sh
#   ./publish.sh -r linux-x64 --clean
#
set -euo pipefail

rid="linux-x64"
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(dirname "$script_dir")"
output_dir="$repo_root/publish-out"
clean=0

while [[ $# -gt 0 ]]; do
    case "$1" in
        -r)      rid="$2"; shift 2 ;;
        -o)      output_dir="$2"; shift 2 ;;
        --clean) clean=1; shift ;;
        *)       echo "Unknown argument: $1" >&2; exit 2 ;;
    esac
done

csproj="$repo_root/src/Mbproxy/Mbproxy.csproj"
if [[ ! -f "$csproj" ]]; then
    echo "Cannot find $csproj" >&2
    exit 1
fi

if [[ "$clean" -eq 1 && -d "$output_dir" ]]; then
    echo "Cleaning $output_dir"
    rm -rf "$output_dir"
fi

# Binary name: Windows RIDs produce an .exe, every other RID an extensionless binary.
if [[ "$rid" == win-* ]]; then bin_name="Mbproxy.exe"; else bin_name="Mbproxy"; fi

self_contained_out="$output_dir/self-contained"
framework_dependent_out="$output_dir/framework-dependent"

echo
echo "=== Publishing self-contained ($rid, ~100 MB) ==="
dotnet publish "$csproj" -c Release -r "$rid" -o "$self_contained_out" --nologo

echo
echo "=== Publishing framework-dependent ($rid, ~1.6 MB) ==="
dotnet publish "$csproj" -c Release -r "$rid" \
    -p:SelfContained=false -p:PublishSingleFile=true -o "$framework_dependent_out" --nologo

echo
echo "=== Result ($rid) ==="
for flavour in self-contained framework-dependent; do
    bin="$output_dir/$flavour/$bin_name"
    if [[ -f "$bin" ]]; then
        size="$(du -h "$bin" | cut -f1)"
        printf '  %-22s %8s  %s\n' "$flavour" "$size" "$bin"
    else
        echo "  WARNING: missing $bin" >&2
    fi
done
echo
