#!/bin/bash
################################################################################
# Copyright 2026 ModalAI Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# 4. The Software is used solely in conjunction with devices provided by
#    ModalAI Inc.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
################################################################################

set -e

APT_FILE="/etc/apt/sources.list.d/modalai.list"
REPO="stable"
USE_APT_TREE=true

__validate_url(){

	wget -S --spider $1  2>&1 | grep -q 'HTTP/1.1 200 OK' && return 0
	return 1
}

__get_available_sections(){

	chip=$(voxl-chip)
	chip_lower=${chip,,}


	# Read lines into an array safely
	mapfile -t REPO_LIST < <(
			wget -q -O- "http://voxl-packages.modalai.com/dists/${chip_lower}/" \
			| grep ' -' \
			| cut -d '>' -f 2 \
			| cut -d '/' -f 1
	)
}

print_usage () {

	local REPO_LIST
	local REPO

	if __validate_url "http://voxl-packages.modalai.com" ; then
		__get_available_sections
	else
		REPO_LIST=( "dev" "sdk-X.Y" "stable" "staging" )
	fi

	echo ""
	echo "Description:"
	echo "        Configure apt/opkg package manager source."
	echo ""
	echo "We recommend leaving the package manager set to pull from the stable"
	echo "repository unless you know what you are doing and wish to pull from"
	echo "the development or staging repositories."
	echo ""
	echo "You may also select a specific sdk-X.Y release repository."
	echo ""
	echo "The wizard option will ask questions if you don't want to give arguments."
	echo "If no args are given, the wizard will start automatically."
	echo ""
	echo "Usage:"
	echo "  voxl-configure-pkg-manager"
	echo "  voxl-configure-pkg-manager help"
	for REPO in ${REPO_LIST[@]} ; do
		echo "  voxl-configure-pkg-manager ${REPO}"
	done
	echo ""

}


process_argument () {

	if [ "$#" -ne 1 ]; then
		echo "ERROR process_argument expected 1 argument"
		exit 1
	fi

	## convert argument to lower case for robustness
	arg=$(echo "$1" | tr '[:upper:]' '[:lower:]')

	## parse arguments
	case ${arg} in
		"h"|"-h"|"help"|"--help")
			print_usage
			exit 0
			;;
		"dev"|"development")
			REPO="dev"
			;;
		"stable")
			REPO="stable"
			;;
		"staging")
			REPO="staging"
			;;
		sdk-*)
			REPO=${arg}
			## can only use the normal apt tree mode for named repos, not sdk-x.y
			USE_APT_TREE=false
			;;
		*)
			echo "invalid option $arg"
			print_usage
			exit 1
	esac
}


run_wizard () {

	local REPO_LIST

	if __validate_url "http://voxl-packages.modalai.com" ; then
		__get_available_sections
	else
		REPO_LIST=( "dev" "stable" "staging" )
	fi

	echo ""
	echo "Which repository do you want to use?"
	echo "stable  - recommended for most users"
	echo "staging - packages under testing for next sdk release"
	echo "sdk-X.Y - Specific SDK release"
	echo "dev     - recommended for ModalAI development team only"
	echo ""

	select opt in "${REPO_LIST[@]}"; do
		if [[ -n "$opt" ]]; then
			REPO="$opt"
			break
		fi
		echo "Invalid option"
	done
}



################################################################################
## actual start of execution
################################################################################

## parse all arguments or run wizard
if [ "$#" -gt 0 ]; then
	for var in "$@"
	do
		process_argument $var
	done
else
	run_wizard
fi

echo "Using repo: ${REPO}"

################################################################################
## now actually configure everything based on the variables set above
################################################################################
chip=$(voxl-chip)
chip_lower=${chip,,}

if [ $USE_APT_TREE == true ]; then
	LINE="deb [trusted=yes] http://voxl-packages.modalai.com/ ${chip_lower} ${REPO}"
else
	LINE="deb [trusted=yes] http://voxl-packages.modalai.com/ ./dists/${chip_lower}/${REPO}/binary-arm64/"
fi

echo "${LINE}" > ${APT_FILE}
echo ""
echo "Done configuring apt sources"
echo "run apt update to pull new repository manifest"

