#! /bin/bash

# ============================================================
# Copyright (2024) Nautel Ltd.
# All rights reserved.
# ============================================================

script_name=$0
script_full_path=$(dirname "$0")

cd $script_full_path
. $script_full_path/variables.sh

mender_upgrade_filename="gaia.mender"
if [ -e "$script_full_path/$mender_upgrade_filename" ]
then
    :
else
    exit 15
fi

if [[ $MACHINE == nape90 ]]; then
    uboot_ver=$(/usr/bin/fw_printenv nape90_uboot_ver | awk -F = '{ print $2 }')
    if [[ "$uboot_ver" = "1.0.0" ]]; then
        fw_setenv altbootcmd 'run mender_altbootcmd; run bootcmd'
        fw_setenv nape90_uboot_ver 1.0.1
    fi
fi

tmp_mender_output_file="/tmp/mender_output.txt"
progress_file="/tmp/upgrade_progress.txt"

mender install $script_full_path/$mender_upgrade_filename 2> $tmp_mender_output_file &
mender_pid=$!

prev_progress_percent=0
while ps -p $mender_pid > /dev/null
do
    progress_dots=$(grep -o '[.]*' $tmp_mender_output_file | awk 'length > max_length {max_length = length; longest = $0} END {print longest}')
    if [ ${#progress_dots} -ne 0 ]; then
        progress_percentage=$((${#progress_dots} * 100 / 69))
        if [ $progress_percentage -ne $prev_progress_percent ]; then
            echo $progress_percentage >> $progress_file
            prev_progress_percent=$progress_percentage
        fi
    fi
    sleep 1
done

wait $mender_pid
ret_code=$?

if [ $ret_code -ne 0 ]; then
    exit 16
fi
