
#!/bin/bash

# This script installs the latest version of ottofms-app on a Linux system.

# Default version
VERSION="latest"

# Detect machine architecture
MACHINE_ARCH=$(uname -m)

# Parse optional -v argument for version
while getopts "v:" opt; do
  case $opt in
    v) VERSION="$OPTARG" ;;
    \?) echo "Invalid option: -$OPTARG" >&2; exit 1 ;;
  esac
done

if [ "$MACHINE_ARCH" = "arm64" ]; then
	DOWNLOAD_URL="https://console.ottomatic.cloud/downloads/ottofms/$VERSION/mac-arm"
	ARCH_FILE_NAME="osx-arm64"
else 
	DOWNLOAD_URL="https://console.ottomatic.cloud/downloads/ottofms/$VERSION/mac"
	ARCH_FILE_NAME="osx-x86_64"
fi

# Function to download and prepare the new version
prepare_new_version() {
	rm -f "$TMPDIR"installer.zip

	echo "Downloading ottofms-app version $VERSION for mac..."
	if curl -L -o "$TMPDIR"installer.zip "$DOWNLOAD_URL"; then
		echo "Download successful."
	else
		echo "Download failed. Exiting."
		exit 1
	fi

	# Unzip the downloaded file and find the directory name
	echo "Unzipping the downloaded file..."
	UNZIP_DIR="$TMPDIR"$(unzip -Z -1 "$TMPDIR"installer.zip | head -n 1 | cut -d '/' -f 1)
	rm -rf "$UNZIP_DIR"
	if unzip -o "$TMPDIR"installer.zip -d $UNZIP_DIR; then
		echo "Unzip successful."
	else
		echo "Unzip failed. Exiting."
		exit 1
	fi

	# Find the .deb file
	APP_FILE=$(find "$UNZIP_DIR" -name "*.app")
	if [ -z "$APP_FILE" ]; then
		echo "No .app file found."
		exit 1
	fi

}

# Function to uninstall the existing version
uninstall_existing_version() {
	if mdfind -name "ottofms-macos" -onlyin /Applications/OttoFMS/bin | grep -q ottofms; then
		echo "ottofms-app is installed. Uninstalling..."
		sudo /Applications/OttoFMS/UninstallOtto.app/Contents/MacOS/$ARCH_FILE_NAME --mode unattended 

		# wait 5 seconds to make sure the uninstallation is complete
		echo "Waiting 5 seconds for post-uninstall to finish..."
		sleep 5
	else
		echo "ottofms-app is not installed."
	fi
}

# Function to clean up files
cleanup_files() {
 echo "Cleaning up files..."
	rm -f "$TMPDIR"installer.zip
	if [ -n "$UNZIP_DIR" ]; then
		rm -rf "$UNZIP_DIR"
	fi
}

# Prepare the new version
prepare_new_version

# Uninstall the existing version, if present
uninstall_existing_version

# Install the new version
echo "Installing $APP_FILE..."
if sudo $APP_FILE/Contents/MacOS/$ARCH_FILE_NAME --mode unattended; then
	echo "Installation successful."
	cleanup_files	
else
	echo "Installation failed."
	cleanup_files
	exit 1
fi
