#!/bin/bash

# Require at least 1 argument
if [ $# -lt 1 ]; then
	echo "Require at least 1 argument."
	exit 1
fi

extract() {
	local file="$1"
	local mimetype="$(file --dereference --brief --mime-type -- "$file")"
	local filename="$(basename "$file")"

	if [[ $filename == @(*.tar.@(zst|gz|lz|lzma|lzo|xz|Z)|*.tb2|*.tz2|*.tbz|*.tbz2|*.taz|*.tgz|*.tlz|*.txz|*.tZ|*.taZ|*.tzst) ]] || [[ $mimetype == @(application/x-?(g)tar*|application/*-compressed-tar) ]]; then
		tar -xf "$file" || bsdtar -xf "$file"
		return
	fi

	if [[ $mimetype == application/zstd ]]; then
		zstd -d "$file"; return
	fi

	if [[ $mimetype == @(application/x-xz*|application/*-xz-compressed) ]]; then
		xz -kd "$file" || bsdtar -xf "$file"
		return
	fi

	if [[ $mimetype == @(application/vnd.rar|application/vnd.comicbook-rar|application/x-rar*) ]]; then
		unrar x -p- -- "$file" || bsdtar -xf "$file"
		return
	fi

	if [[ $mimetype == application/x-7z-compressed ]]; then
		7z x -p -- "$file" || bsdtar -xf "$file"
		return
	fi

	if [[ $mimetype == @(application/vnd.efi.iso|application/x-*-rom|application/x-compressed-iso|application/x*-iso?(9660)-?(app)image) ]]; then
		isoinfo -X -i "$file" || bsdtar -xf "$file"
		return
	fi

	if [[ $mimetype == application/x-cpio* ]]; then
		cpio -iF "$file" || bsdtar -xf "$file"
		return
	fi

	if [[ $mimetype == application/?(x-)gzip ]]; then
		bsdtar -xf "$file" || gzip -d "$file"
		return
	fi

	if [[ $mimetype == @(application/vnd.ms-cab-compressed|application/x-archive|application/?(x-)bzip*|application/x-lzma|application/x-lzip|application/x-lha|application/x-lzh-compressed|application/x-lhz|application/x-lzop|application/x-lz4|application/x-lrzip) ]]; then
		bsdtar -xf "$file"; return
	fi

	echo "File $file with mimetype $mimetype is not supported."
	return 1
}

for file in "$@"; do
	extract "$file" || exit 1
done
