#!/usr/bin/env bash
set -euo pipefail

# Get the directory where this stub is located
STUB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MAILPIT_BINARY="$STUB_DIR/mailpit-binary"

# If binary exists, immediately replace this script process with the binary
if [ -f "$MAILPIT_BINARY" ]; then
    exec "$MAILPIT_BINARY" "$@"
fi

# Binary doesn't exist, so download it
echo "Mailpit binary not found. Downloading..."

BASE_URL="https://github.com/axllent/mailpit/releases/download/v1.24.2"
TMP_DIR=$(mktemp -d)

# Determine platform and architecture
case "$(uname -s)" in
    Darwin) PLATFORM="darwin" ;;
    Linux)  PLATFORM="linux" ;;
    *)      echo "Unsupported platform: $(uname -s)" >&2; exit 1 ;;
esac

case "$(uname -m)" in
    x86_64|amd64) ARCH="amd64" ;;
    arm64|aarch64) ARCH="arm64" ;;
    *)      echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac

ARCHIVE_NAME="mailpit-${PLATFORM}-${ARCH}.tar.gz"
DOWNLOAD_URL="$BASE_URL/$ARCHIVE_NAME"

# Download and extract
echo "Downloading $DOWNLOAD_URL"
curl -fsSL "$DOWNLOAD_URL" -o "$TMP_DIR/$ARCHIVE_NAME"

echo "Extracting..."
tar -xzf "$TMP_DIR/$ARCHIVE_NAME" -C "$TMP_DIR"

# Move binary to the expected location
mv "$TMP_DIR/mailpit" "$MAILPIT_BINARY"
chmod +x "$MAILPIT_BINARY"

# Cleanup
rm -rf "$TMP_DIR"
echo "Download complete!"

# Now replace this script process with the binary
exec "$MAILPIT_BINARY" "$@"
