#!/bin/sh

set -e

export TEXTDOMAIN=kcm_mobile_update_scripts
. gettext.sh

help() {
	arg0=$0
	echo $(eval_gettext "Usage: \$arg0 [-p UPDATE_URI_LINK ]") >&2
	exit 1
}

while getopts ":s:p:" o; do
    case "${o}" in
        p)
            p=${OPTARG}
            ;;
        *)
            help
            ;;
    esac
done
shift $((OPTIND-1))

last_version_file=/etc/astra-mobile-update/last_version
current_script_path=$(dirname "$(readlink -f "$0")")

$current_script_path/check-battery
$current_script_path/check-space

updates=$($current_script_path/list-of-updates)

if [ -z $p ]; then
	while true; do
		echo $(gettext "Select update:")
		i=1
		for update in $updates; do
			echo "$i) `echo $update | tr "!" "/"`"
			i=$(expr $i + 1)
		done

		read -p "$(gettext "Enter update index: ")" update_index
	    if [ $update_index -gt 0 ] && [ $update_index -le $i ]; then
	    	p=$(echo $updates | cut -d' ' -f $update_index | tr "!" "/")
	    	break;
	    else
	    	echo $(eval_gettext "Wrong index: \$update_index")
	    fi
	done
fi

filename=$(basename $p)

if [ -f ~/update/$filename ] && [ -f ~/update/${filename}.gost ]; then
	echo $(eval_gettext "Update \$filename is local file")
else
	$current_script_path/download-update-file $p
fi
$current_script_path/check-sum $filename
echo $(eval_gettext "Update file is: \$filename")
sudo $current_script_path/run-update-script-from-img ~/update/$filename
