#!/bin/bash
GPGPASSWDFILE="${HOME}/.gnupg/support.pw"

ARCHIVE=$1
if [ -z "$ARCHIVE" ]; then
	ARCHIVE="$( ls univention-support-info-*.tar.bz2 univention-support-info-*.tar.bz2.gpg upload_*.bz2 upload_*.asc upload_*.bin upload_*.unknown 2>/dev/null )"
fi

if [ -d "$ARCHIVE" ]; then
	usi-check -u "$( pwd )""$ARCHIVE"

else

	for A in $ARCHIVE; do
		if [ -r "$A" ]; then
			GPGA=""

			# reliable detect gpg encrypted files
			fileType=$( file -b "${A}" | awk -F- '{print $1}' | sed 's/^ //;s/ $//' )
			if [ "PGP RSA encrypted session key" == "$fileType" -o "GPG encrypted data" == "$fileType" ]; then
				GPGA=${A}
				A="$(basename $GPGA .gpg)"
				[[ "$A"  != *.tar.bz2 ]] && A="${A}.tar.bz2"
			fi

			# decrypt gpg file
			if [ -n "$GPGA" ]; then
				if [ ! -r $GPGPASSWDFILE ]; then
					echo "Archive is encrypted but no password file was found!"
					echo "Please add a file \"$GPGPASSWDFILE\" containing the passphrase for the support gpg key"
					exit 1
				fi

				# parse it and try all passwords inside (line by line)
				encret=-1
				while IFS='' read -r PASSPHRASE || [[ -n "$PASSPHRASE" ]]; do
					gpg --quiet --passphrase "$PASSPHRASE" -d "$GPGA" > "$A"
					encret=$?
					if [ $encret -eq 0 ]; then
						break
					elif [ $encret -eq 2 ]; then
						echo -e "\nusi: Probably wrong passphrase! Trying next key in file '$GPGPASSWDFILE'..."
					fi
				done <"$GPGPASSWDFILE"
				if [ ! -s "$A" ]; then
					echo -e "Decryption of Archive '${GPGA}' failed!\nDeleting empty file '$A'."
					rm "$A"
					exit 1
				fi
			fi
			# extract archive
			usiname="$(tar -tf $A | head -1 | cut -d"/" -f1)"
			usifolder="$( tar -tf $A | head -1 | sed 's/univention-support-info-//;s/Z\/.*$//' )"
			if [[ "$OSTYPE" == "darwin"* ]]; then
				tar -xjf $A -p
			else
				tar -xjf $A --atime-preserve
			fi
			tarret=$?

			# simple folder name
			if [ -f "univention-support-info" ]; then
				echo "ERR: There is already a file named 'univention-support-info'!"
				exit 3
			elif [ ! -d "univention-support-info" ]; then
				mkdir univention-support-info
			fi
			mv "${usiname}" "univention-support-info/${usifolder}"

			# cleanup
			if [ $tarret -eq 0 ] && [ -z "$GPGA" ]; then
				# delete archive
				echo -e "removing '${A}'"
				rm "${A}"
			elif [ $tarret -eq 0 ] && [ -n "$GPGA" ]; then
				# don't delete archive if it was encrypted
				echo -e "keeping '${A}'"
			fi
			if [ -n "${encret+x}" ] && [ ${encret} -eq 0 ]; then
				echo -e "removing '${GPGA}'"
				rm "${GPGA}"
			fi

			if [ -n "$( whereis usi-check | cut -d' ' -f2 )" ]; then
				usi-check -u "$( pwd )""/univention-support-info/${usifolder}"
			fi
		fi
	done
fi

