#!/bin/sh -e
# ex - archive extractor
# adapted and improved from the commonly circulating version
# detects whether unpacking into a subfolder is sensible
# and shows progress indications for some operations
# optdepends: rewrite(part of my dotfiles)
for arg do
	if test -r "$arg"; then
		fullpath="$(realpath "$arg")"
		name="$(basename "${fullpath%.*}")"
		namepart="$name.part"
		(
		if test "$(ls -U | wc -l)" -gt 2; then
			mkdir -p "$namepart"
			cd "$namepart"
		fi
		echo "Extracting $arg into $PWD"
		case "$arg" in
			(*.tar.*|*.tar) tar --extract --file "$fullpath";;
			(*.tbz2)        tar xjf "$fullpath"   ;;
			(*.tgz)         tar xzf "$fullpath"   ;;
			(*.7z|*.z01|*.zip|*.jar)
				if which 7z >/dev/null
				then 7z x "$fullpath"
				else unzip "$fullpath" | rewrite
				fi;;
			(*.gz)          gunzip "$fullpath"    ;;
			(*.bz2)         bunzip2 "$fullpath"   ;;
			(*.rar)         unrar x "$fullpath"   ;;
			(*.deb)         ar x "$fullpath"      ;;
			(*.zst)         unzstd "$fullpath"    ;;
			(*.Z)           uncompress "$fullpath";;
			(*)             echo "'$arg' cannot be extracted by ex" >&2;;
		esac
		test "$(basename "$PWD")" = "$namepart" &&
			if test $# -lt 2 -a "$(ls -U | wc -l)" -lt 3
			then mv * .. && cd .. && rm -d "$namepart"
			else cd .. && mv "$namepart" "$name"
			fi
		)
	else
		echo "'$1' is not a readable file"
	fi
done