#!/bin/bash

ENC=( 'UTF-8'         'UTF-16BE'  'UTF-16LE'  'UTF-32BE'          'UTF-32LE')
BOM=($'\xEF\xBB\xBF' $'\xFE\xFF' $'\xFF\xFE' $'\x00\x00\xFE\xFF' $'\x00\x00\xFF\xFE')
TXT='TEST'
DIR='TEST'
SRC="/opt/novell/zenworks/install/downloads/${DIR}"

mkdir --parent "${SRC}"
pushd          "${SRC}"

# iterate over encodings
for i in ${!ENC[@]}; do

	FILE="${ENC[$i]}.txt"

	# Generate test file with BOM in enconding
	echo "${ENC[$i]} $(echo ${BOM[$i]} | xxd)"
	echo -n "${BOM[$i]}"              > "${FILE}"
	echo -n "${TXT}" | iconv -f 'UTF-8' -t "${ENC[$i]}" >> "${FILE}"
	
	# get test file through HTTP, always redownload
	rm "/tmp/${FILE}"
	wget \
		--no-verbose \
		--no-check-certificate \
		"https://localhost/zenworks-downloads/${DIR}/${FILE}" \
		--server-response \
		--directory-prefix='/tmp/' \
		--no-clobber \
		--read-timeout=3


done

# iterate over encodings
for i in ${!ENC[@]}; do

	FILE="${ENC[$i]}.txt"

	# compare test file to download
	diff <(xxd "${SRC}/${FILE}") <(xxd "/tmp/${FILE}") \
	|| md5sum "${SRC}/${FILE}" "/tmp/${FILE}"

done

diff \
	--report-identical-files \
	--recursive \
	"${SRC}/" '/tmp/' \
| grep 'identical$'

popd

