#!/bin/bash
# CustomAppGateway Universal Installer
# https://customappgateway.appx.uk

set -e

BASE_URL="https://customappgateway.appx.uk"
INSTALLER_NAME="cag-installer"
TEMP_DIR="/tmp/cag-installer-$(date +%s)"
BINARY_PATH="$TEMP_DIR/$INSTALLER_NAME"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${BLUE}CustomAppGateway Universal Installer${NC}"
echo "----------------------------------------"

# 1. Auto-Detect OS and Arch
OS="$(uname -s)"
ARCH="$(uname -m)"

case "$OS" in
    Linux)
        OS_TYPE="linux"
        ;;
    Darwin)
        OS_TYPE="macos"
        ;;
    MINGW*|MSYS*|CYGWIN*)
        OS_TYPE="win.exe"
        ;;
    *)
        echo -e "${RED}Unsupported Operating System: $OS${NC}"
        exit 1
        ;;
esac

# Simple arch check (pkg usually bundles for x64, we need to verify if we have arm64 builds)
# For now, assuming the binaries we build are x64 compatible (Rosetta on Mac ARM) or we have specific builds.
# The user only mentioned standard binaries. I'll stick to the names we have.
# If we add ARM later, we'll need to update this.
# For now, just map to the filenames we have.

BINARY_URL="$BASE_URL/$INSTALLER_NAME-$OS_TYPE"

echo -e "Detected OS: $OS ($ARCH)"
echo -e "Downloading installer from: $BINARY_URL"

# 2. Download Binary
mkdir -p "$TEMP_DIR"
if command -v curl >/dev/null 2>&1; then
    curl -sL -o "$BINARY_PATH" "$BINARY_URL"
elif command -v wget >/dev/null 2>&1; then
    wget -q -O "$BINARY_PATH" "$BINARY_URL"
else
    echo -e "${RED}Error: Neither curl nor wget found.${NC}"
    exit 1
fi

chmod +x "$BINARY_PATH"

# 3. Execute
echo -e "${GREEN}Running Installer...${NC}"
echo "----------------------------------------"

# Ensure we can read from TTY if interactive input is needed
if [ -t 0 ]; then
    # stdin is already a TTY
    "$BINARY_PATH" "$@"
else
    # Try to re-attach to TTY if available (e.g. when piped from curl)
    if [ -e /dev/tty ]; then
        "$BINARY_PATH" "$@" < /dev/tty
    else
        "$BINARY_PATH" "$@"
    fi
fi

EXIT_CODE=$?

# 4. Auto-Cleanup
echo ""
echo "----------------------------------------"
echo -e "${BLUE}Cleaning up...${NC}"
rm -rf "$TEMP_DIR"

if [ $EXIT_CODE -eq 0 ]; then
    echo -e "${GREEN}Done.${NC}"
else
    echo -e "${RED}Installer exited with error code $EXIT_CODE${NC}"
fi

exit $EXIT_CODE
