#!/bin/bash
# A general, all-purpose extraction script. Not all extraction programs here
# are installed by LARBS automatically.
#
# Default behavior: Extract archive into new directory
# Behavior with `-c` option: Extract contents into current directory

while getopts "hc" o; do case "${o}" in
	c) extracthere="True" ;;
	*) printf "Options:\\n   -c: Extract archive into current directory rather than a new one.\\n" && exit ;;
esac done

extractfunc(){
toextract="$1"
case "$archive" in
	*.tar.bz2|*.tbz2) tar xvjf "$toextract" ;;
	*.tar.xz) tar -xf "$toextract" ;;
	*.tar.gz|*.tgz) tar xvzf "$toextract" ;;
	*.lzma) unlzma "$toextract" ;;
	*.bz2) bunzip2 "$toextract" ;;
	*.rar) unrar x -ad "$toextract" ;;
	*.gz) gunzip "$toextract" ;;
	*.tar) tar xvf "$toextract" ;;
	*.zip) unzip "$toextract" ;;
	*.Z) uncompress "$toextract" ;;
	*.7z) 7z x "$toextract" ;;
	*.xz) unxz "$toextract" ;;
	*.exe) cabextract "$toextract" ;;
	*.zst) zstd -d "$toextract";;
	*) printf "extract: '%s' - unknown archive method\\n" "$toextract" ;;
esac
}
archives="$(readlink -f "${@##-c}" )"
while read -r archive; do
	directory="$(echo "$archive" | sed 's/\.[^\/.]*$//')" &&
	if [ -f "$archive" ];then
		if [ -z "$extracthere" ]; then
			mkdir -p $directory &&
			cd "$directory" || exit
		fi
		extractfunc "$archive"
	else
		printf "File \"%s\" not found.\\n" "$archive"
	fi
done < <(echo "$archives")

[ "$archives" = "" ] && printf "Give archive to extract as argument.\\n" && exit