#!/bin/sh

set -e

export TEXTDOMAIN=kcm_mobile_update_scripts
. gettext.sh

update_list=/etc/astra-mobile-update/update.list

top_pid=$$

architecture=$(uname -m)

get_version_from_filename() {
	# example: astra-mobile-update_0.1.0.img .img
	filename=$1
	extension=$2

	echo $filename | cut -d'_' -f2- | sed "s/\(.*\)$extension/\1/"
}

httpSource() {
	source=$1

	files=$(curl -f -s --connect-timeout 5 $source | grep -o 'href=".*">' | sed 's/href="//' | sed 's/\">//')
	if [ -z "$files" ]; then
		echo $(eval_gettext "Can't open \$source") >&2
		kill -s TERM $top_pid # exit 1 didn't work
	fi

	for file in $files; do
		if [[ $file == *$architecture.img ]]; then
			echo "$source!$file"
		fi
	done
}

localFileSource() {
	source=$1

	local_path=$(echo $source | sed 's#file://##g')
	files=$(ls -1 $local_path)

	for file in $files; do
		if [[ $file == *$architecture.img ]]; then
			echo "$source!$file"
		fi
	done
}

ftpSource() {
	source=$1

	files=$(curl -f -s --connect-timeout 5 --list-only $source/)
	if [ -z "$files" ]; then
		echo $(eval_gettext "Can't open \$source") >&2
		kill -s TERM $top_pid # exit 1 didn't work
	fi

	for file in $files; do
		if [[ $file == *$architecture.img ]]; then
			echo "$source!$file"
		fi
	done
}

### MAIN ###

# remove emty space and # from file, after read lines
sed -E '/^[[:blank:]]*(#|$)/d; s/#.*//' $update_list | while read source; do
	# http / https ls command
	if [[ $source == "http://"* ]] || [[ $source == "https://"* ]]; then
		httpSource $source
	fi
	if [[ $source == "file://"* ]]; then
		localFileSource $source
	fi
	if [[ "$source" == "ftp://"* ]]; then
		ftpSource $source
	fi
done
