#!/bin/bash

# Configuration variables
INSTALLER_NAME="MyZenV2s-setup.pkg"
DOWNLOAD_URL_ARM="https://portal.we360.ai/static/binaries/latest/MyZenV2s-arm64.pkg"
DOWNLOAD_URL_INTEL="https://portal.we360.ai/static/binaries/latest/MyZenV2s-amd64.pkg"
FORCE_INSTALL=true  # Set to false to skip if already installed

# Function to check if ZS is already installed
function test_zs_installation {
    if [ -e /usr/local/zs/zs.app/Contents/MacOS/zs ] ; then
        return 0  # ZS is installed
    else
        return 1  # ZS is not installed
    fi
}

# Validate installer name
if [[ -z "$INSTALLER_NAME" ]]; then
    echo "Installer name cannot be empty" >&2
    exit 1
fi

# Ensure installer name has .pkg extension
if [[ "${INSTALLER_NAME##*.}" != "pkg" ]]; then
    INSTALLER_NAME="$INSTALLER_NAME.pkg"
fi

# Check if software is already installed and ForceInstall is not set
if test_zs_installation && [ "$FORCE_INSTALL" = false ]; then
    echo "ZS is already installed. Set FORCE_INSTALL=true to reinstall anyway."
    exit 0
fi

# Determine the architecture and set the appropriate download URL
ARCH=$(uname -m)
if [[ "$ARCH" == "arm64" ]]; then
    echo "Using ARM installer"
    DOWNLOAD_URL="$DOWNLOAD_URL_ARM"
else
    echo "Using Intel installer"
    DOWNLOAD_URL="$DOWNLOAD_URL_INTEL"
fi

# Create temporary file path with custom name
TEMP_FILE="/tmp/$INSTALLER_NAME"

# Download the installer
echo "Downloading installer to temporary location: $TEMP_FILE"
if ! curl -L "$DOWNLOAD_URL" -o "$TEMP_FILE"; then
    echo "Failed to download the installer" >&2
    rm -f "$TEMP_FILE"
    exit 1
fi

# Install the software
echo "Installing software..."
if [ "$FORCE_INSTALL" = true ]; then
    echo "Force install enabled - proceeding with installation regardless of existing version"
fi

if ! sudo installer -pkg "$TEMP_FILE" -target /; then
    echo "Installation failed" >&2
    rm -f "$TEMP_FILE"
    exit 1
fi

echo "Installation completed successfully."

# Cleanup
rm -f "$TEMP_FILE"

exit 0