#!/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 licensed to be 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.
################################################################################

SHOW_PACKAGES=true
JSON=false

print_usage () {
    echo ""
    echo "Prints out version information of the voxl system"
    echo ""
    echo "arguments are as follows:"
    echo ""
    echo "    -h | --help       - show this help text"
    echo "    -j | --json       - output in json format"
    echo "    -q | --quiet      - don't show the long list of packages"
    echo ""
    echo ""
}

parse_opts(){

    while [[ $# -gt 0 ]]; do

        ## 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
                ;;
            "-j"|"--json")
                JSON=true
                ;;
            "-q"|"--quiet")
                SHOW_PACKAGES=false
                ;;
            *)
                ## all other arguments are invalid
                echo "invalid option $arg"
                print_usage
                exit -1
        esac
        shift
    done
}

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

parse_opts $@

kversion=$(uname -v)
krelease=$(uname -r)
platform=$(voxl-platform)

# set default machine and variant number for system without the voxl_platform_mod kernel module
pmod_machine="1"
pmod_variant="0"
pmod_config="0"
pmod=$pmod_machine"."$pmod_variant"."$pmod_config

case $platform in

    M0205 | M0204 | M0104 | M0054 | M0052)
        # QRB5165
        sysimg=$(cat /etc/version)

        # starting sys img 1.7.3, we export info from voxl-platform-mod.ko
        if [ -d "/sys/module/voxl_platform_mod/parameters" ]; then
            pmod_machine=$(cat /sys/module/voxl_platform_mod/parameters/machine)
            pmod_variant=$(cat /sys/module/voxl_platform_mod/parameters/variant)
            pmod_config=$(cat /sys/module/voxl_platform_mod/parameters/config)
            pmod=$pmod_machine"."$pmod_variant"."$pmod_config
        fi
        ;;

    M0197)
        # QCS6490
        sysimg=$(dpkg-query --showformat='${Version}' --show voxl3-system-image 2>/dev/null) || sysimg=""
        
        if [ -d "/sys/devices/platform/voxl" ]; then
            pmod_machine=$(cat /sys/devices/platform/voxl/machine)
            pmod_variant=$(cat /sys/devices/platform/voxl/variant)
            pmod_config=$(cat /sys/devices/platform/voxl/config)
            pmod=$pmod_machine"."$pmod_variant"."$pmod_config
        fi
        ;;

    *)
        sysimg=$(uname -r)
        pmod="0.0.0"
        ;;
esac

suite=$(dpkg --status voxl-suite | grep '^Version:' | cut -d ' ' -f 2)

# JSON output
if [ "${JSON}" = true ] ; then
    dpkg -l | tr -s ' ' ',' | cut -d ',' -f 2-3 | egrep -i "voxl|libfc-sensor|modal|qrb5165" > packages_temp.txt

    packages_json="{"
    while IFS=, read -r package version; do # read temp file and split by commas
        packages_json+="\"${package}\":\"${version}\","
    done < packages_temp.txt

    # Remove last comma and close JSON object
    packages_json="${packages_json%,}"
    packages_json+="}"

    # append packages_json into sdk_json
    sdk_json=$(printf '{"systemImage": "%s","kernel": "%s %s","hwVersion": "%s","platformMod": "%s","voxlSuite": "%s","packages": %s}\n' "$sysimg" "$kversion" "$krelease" "$platform" "$pmod" "$suite" "$packages_json")

    # Output whole JSON
    echo "${sdk_json}"

    # Remove the temp file
    rm packages_temp.txt

    exit 0
else
    echo "────────────────────────────────────────────────────────────────────────────────"
    echo -e "${SET_BOLD}${CLR_GRN}system-image${RESET_ALL}: $sysimg"
    echo -e "${SET_BOLD}${CLR_GRN}kernel${RESET_ALL}:       $kversion $krelease"
    echo "────────────────────────────────────────────────────────────────────────────────"
    echo -e "${SET_BOLD}hw platform${RESET_ALL}:  $platform"
    echo -e "${SET_BOLD}mach.var${RESET_ALL}:     $pmod"
    # Add SKU info if available
    if [ -f /data/modalai/sku.txt ]; then
        SKU=$(cat /data/modalai/sku.txt)
        echo -e "${SET_BOLD}${CLR_GRN}SKU${RESET_ALL}:          $SKU"
    fi
    echo "────────────────────────────────────────────────────────────────────────────────"
    echo -e "${SET_BOLD}${CLR_GRN}voxl-suite${RESET_ALL}:   $suite"
    echo "────────────────────────────────────────────────────────────────────────────────"
fi

# -q | --quiet arg
if ! ${SHOW_PACKAGES} ; then
    exit 0
fi


echo -e "${SET_BOLD}${CLR_GRN}Packages${RESET_ALL}:"


echo -n "Repo: "
cat /etc/apt/sources.list.d/modalai.list | cut -d ']' -f 2

echo -n "Last Updated: "
stat -c '%y' /var/lib/apt/lists/partial/ | cut -d '.' -f 1

if [[ $(stat -c '%Y' /etc/apt/sources.list.d/modalai.list ) > $(stat -c '%Y' /var/lib/apt/lists/partial/ ) ]] ; then
    echo -e "${CLR_YLW}WARNING: repo file has changed since last update,\n\tpackages may have originated from a different repo${RESET_ALL}"
fi

echo    "List:"

## old way for backup
## dpkg -l | tr -s ' ' ',' | cut -d ',' -f 2-3 | egrep -i "voxl|libfc-sensor|modal|qrb5165" | column -t -s "," | paste /dev/null -

## new way, a bit faster
dpkg-query --showformat='${Package},${Version},${Status}\n' --show "*voxl*" "*qrb5165*" "*modal*" "*libfc-sensor*" 2>/dev/null | grep "install ok" | cut -d ',' -f 1-2 | column -t -s ","



echo "────────────────────────────────────────────────────────────────────────────────"

