#!/bin/bash
BUILD="latest"
ARCH=$(dpkg --print-architecture)
OS=$(grep -Eoi 'Raspbian|Debian|Ubuntu' /etc/issue)
LIST_VERSIONS=false
APP="uavcast"

# Base URL - can be overridden with environment variable for development
BASE_URL="${INSTALLER_BASE_URL:-https://install.uavmatrix.com}"

YELLOW='\033[1;33m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

while getopts b:l option
do
 case "${option}"
 in
 b) BUILD=${OPTARG};;
 l) LIST_VERSIONS=true;;
 esac
done 

# If list versions flag is set, fetch and display available versions
if [ "$LIST_VERSIONS" = true ]; then
    printf "\n${BLUE}Fetching available versions for $OS $ARCH...${NC}\n\n"
    VERSIONS_URL="${BASE_URL}/versions?arch=$ARCH&app=$APP"

    # Fetch versions as JSON array
    VERSIONS=$(curl -s ${VERSIONS_URL})

    # Check if we got a valid response
    if [ -z "$VERSIONS" ] || [[ "$VERSIONS" == *"No available versions"* ]] || [[ "$VERSIONS" == *"404"* ]]; then
        printf "${YELLOW}No versions available for your architecture ($ARCH)${NC}\n\n"
        exit 1
    fi

    # Check if jq is available for better JSON parsing
    if command -v jq &> /dev/null; then
        printf "${GREEN}Available versions:${NC}\n"
        echo "$VERSIONS" | jq -r '.[]' | nl -w2 -s'. '
    else
        # Fallback: parse JSON manually (simple array)
        printf "${GREEN}Available versions:${NC}\n"
        echo "$VERSIONS" | sed 's/^\[//;s/\]$//;s/"//g' | tr ',' '\n' | nl -w2 -s'. '
    fi

    printf "\n${BLUE}To install a specific version, use:${NC}\n"
    printf "  curl -fsSL ${BASE_URL} | bash -s -- -b <version>\n\n"
    exit 0
fi

cleanup_installation_directory() {
    # Files and directories to delete
    declare -a delete_list=(
        "build"
        "dist"
        "factory"
        "install"
    )

    # Check if installation directory exists
    if [ ! -d "/opt/uavcast-pro" ]; then
        return 0
    fi

    # Remove specified files and directories
    for item in "${delete_list[@]}"; do
        path="/opt/uavcast-pro/$item"
        if [ -f "$path" ]; then
            sudo rm "$path" > /dev/null 2>&1
        elif [ -d "$path" ]; then
            sudo rm -rf "$path" > /dev/null 2>&1
        fi
    done
    return 0
}

URL="${BASE_URL}/bin?arch=${ARCH}&version=${BUILD}&app=${APP}"
FILENAME="uavcast-pro.tar"
DOWNLOAD_DIR="/var/tmp"

printf "\n${BLUE}Installing UAVcast version: ${GREEN}$BUILD${NC}\n"
printf "${BLUE}Architecture: ${GREEN}$ARCH${NC}\n\n"

# Ensure download directory exists
if [ ! -d "${DOWNLOAD_DIR}" ]; then
    sudo mkdir -p "${DOWNLOAD_DIR}"
fi

sleep 1
sudo curl ${URL} -o ${DOWNLOAD_DIR}/${FILENAME}

if ! { tar ztf "${DOWNLOAD_DIR}/${FILENAME}" || tar tf "${DOWNLOAD_DIR}/${FILENAME}"; } >/dev/null 2>&1; then
    printf "\n${YELLOW}No installation candidate for $OS $ARCH found!${NC}\n\n"
    exit
fi

# Run cleanup before extracting new files
cleanup_installation_directory

sudo tar -xvf ${DOWNLOAD_DIR}/${FILENAME} -C /opt > /dev/null 2>&1

# Debug: Check what exists after extraction
printf "${BLUE}Checking for installation scripts...${NC}\n"

# If /opt/uavcast-pro/factory/ApplicationInstaller exists, run it. Otherwise, run /opt/uavcast-pro/factory/install.sh
if sudo [ -f /opt/uavcast-pro/factory/ApplicationInstaller ]; then
    printf "${GREEN}Found ApplicationInstaller, starting installation...${NC}\n"
    sudo chmod +x /opt/uavcast-pro/factory/ApplicationInstaller
    sudo /opt/uavcast-pro/factory/ApplicationInstaller
# fallback to install script for older versions
elif sudo [ -f /opt/UAVcast-Pro/install/install ]; then
    printf "${GREEN}Found legacy install script, starting installation...${NC}\n"
    cd /opt/UAVcast-Pro/install
    sudo ./install

    #Restart Server
    if ! systemctl is-active --quiet UAVcast-Web
    then
        sudo systemctl enable UAVcast-Web
        sudo systemctl start UAVcast-Web
    else
        sudo systemctl restart UAVcast-Web
    fi
else
    printf "\n${YELLOW}No installation script found!${NC}\n\n"
    exit
fi

sleep 3
rm -r ${DOWNLOAD_DIR}/${FILENAME}

