#!/bin/bash
set -e

# Change directory to client folder if not already there
cd "$(dirname "$0")"

echo "============================================="
echo "        BUILDING SECURE WAILS CLIENT         "
echo "============================================="

# Setup Go path for tools like garble and wails
GOPATH=$(go env GOPATH)
if [ -n "$GOPATH" ] && [ -d "$GOPATH/bin" ]; then
    export PATH="$GOPATH/bin:$PATH"
fi
if [ -d "$HOME/go/bin" ]; then
    export PATH="$HOME/go/bin:$PATH"
fi

# Ensure Garble is installed
if ! command -v garble &> /dev/null; then
    echo "[*] Garble is not installed. Installing mvdan.cc/garble@latest..."
    go install mvdan.cc/garble@latest || echo "[!] Failed to install Garble. Will use default Go compiler."
fi

# Check if wails is installed
WAILS_CMD="wails"
if ! command -v wails &> /dev/null; then
    if [ -f "$HOME/go/bin/wails" ]; then
        WAILS_CMD="$HOME/go/bin/wails"
        echo "[*] Found Wails CLI at $WAILS_CMD"
    else
        echo "[-] Wails CLI not found. Please install Wails first."
        echo "    Run: go install github.com/wailsapp/wails/v2/cmd/wails@latest"
        exit 1
    fi
fi

# Set compiler and obfuscation flags if garble is available
BUILD_FLAGS=(-clean -obfuscated -trimpath -m)
if command -v garble &> /dev/null; then
    echo "[*] Garble found. Compiling with Obfuscator..."
    BUILD_FLAGS+=(-compiler garble)
else
    echo "[!] Garble not found. Compiling with default Go compiler..."
fi
BUILD_FLAGS+=(-ldflags "-s -w")

# Detect host OS
HOST_OS=$(go env GOOS)

if [ "$HOST_OS" = "darwin" ]; then
    echo "[*] Building macOS Apple Silicon (arm64)..."
    "$WAILS_CMD" build -platform darwin/arm64 "${BUILD_FLAGS[@]}"

    echo "[*] Building macOS Intel (amd64)..."
    "$WAILS_CMD" build -platform darwin/amd64 "${BUILD_FLAGS[@]}"
    echo "[+] macOS arm64 and amd64 builds completed successfully!"
elif [ "$HOST_OS" = "linux" ]; then
    echo "[*] Building Linux Intel/AMD64 (amd64)..."
    "$WAILS_CMD" build -platform linux/amd64 -tags webkit2_41 "${BUILD_FLAGS[@]}"
    echo "[+] Linux amd64 build completed successfully!"
else
    echo "[!] Unsupported host OS: $HOST_OS. Please build manually using 'wails build'."
    exit 1
fi
