#!/bin/sh
set -e

argv0="$0"
argv1="$1"
argv2="$2"

dep() {
	! command -v "$1" >/dev/null 2>&1 \
		&& printf "%s: Missing dependency for this operation with type %s: %s\n" \
			"$argv0" "$argv2" "$1" 1>&2 \
			&& exit 1 \
		|| return 0
}

deps() {
	while [ -n "$1" ]; do
	# shellcheck disable=SC2015
		command -v "$1" >/dev/null 2>&1 \
			&& printf "%s" "$1" && return 0 \
			|| true
	done
	return 1
}

error() {
	printf "%s: Programmer error. Please report.\n" "$argv0" 1>&2
	exit 1 || return 1
}

# this will alias GNU and busybox lses to the functionality of 9 ls
# - this is a stupid hack and GNU and busybox lses should do this
# by default
# shellcheck disable=SC2015
ls --version >/dev/null 2>&1 || ls -x >/dev/null 2>&1 \
	&& alias ls="ls -1A ." \
	|| alias ls="ls ."

usage() {
	printf "Usage: %s {c,cf,d,df} [type]\n" "$argv0" 1>&2
	exit 1
}

unsupported() {
	printf "%s: Unknown/unsupported type %s for this operation\n" "$argv0" "$argv2" 1>&2
	exit 1
}

[ -z "$3" ] || usage

case "$argv1" in
c)
	case "$argv2" in
	gzip)
		dep gzip
		gzip -c
		# -c - output to standard output
		;;
	xzip)
		dep xz
		xzip -c
		# -c - output to standard output
		;;
	*) unsupported ;;
	esac ;;
d)
	case "$argv2" in
	gzip)
		dep gzip
		gzip -cd
		# -c - output to standard output
		# -d - decompress
		;;
	lzip)
		# should be improved but is decent
		method=$(deps lzip 7z)
		[ -n "$method" ] || dep 7z
		case $method in
		7z)
			7z x -bd -si -so -tlzip
			# x - extract
			# -bd - disable percentage indicator
			# -si - read from standard input
			# -so - output to standard output
			# -tlzip - type: lzip
			;;
		lzip)
			lzip -cd
			# -c - output to standard output
			# -d - decompress
			;;
		*)
			error
			;;
		esac ;;
	tar)
		dep tar
		tar -xO
		# -x - extract
		# -O - output to standard output
		;;
	xzip)
		dep xz
		xz -cd
		# -c - output to standard output
		# -d - decompress
		;;
	*) unsupported ;;
	esac ;;
cf)
	case "$argv2" in
	*) unsupported ;;
	esac ;;
df)
	case "$argv2" in
	tar)
		dep tar
		tar -x
		;;
	unrar)
		# UNTESTED
		unrar x - "$3"
		# x - extract
		# - - stop parsing switches
		;;
	zip)
		# unzip can't extract files that start with a dash as far as I
		# can tell, so we have to use 7z(1)
		dep 7z
		7z x -bd -o. -si -tzip >/dev/null
		# x - extract
		# -bd - disable percentage indicator
		# -o. - output to current dir
		# -si - read from standard input
		# -tzip - type: zip
		;;
	*) unsupported ;;
	esac ;;
*) usage ;;
esac
