#!/bin/sh

if [ -n "$1" ]; then
    if [ -f "$1" ]; then
        printf -- "%s\n" "Extracting $1 ..."
        extract_dir=$(echo "$1" | cut -d'.' -f1)
        case "$1" in
            *.tar.gz|*.tgz) tar zxvf "$1" ;;
            *.tar.bz2|*.tbz|*.tbz2) tar xvjf "$1" ;;
            *.tar.xz|*.txz) tar --xz -xvf "$1" || xzcat "$1" | tar xvf - ;;
            *.tar.zma|*.tlz) tar --lzma -xvf "$1" || lzcat "$1" | tar xvf - ;;
            *.tar.zst|*.tzst) tar --zstd -xvf "$1" || zstdcat "$1" | tar xvf - ;;
            *.tar|*.tar.lz) tar xvf "$1" ;;
            *.tar.lz4) lz4 -c -d "$1" | tar xvf - ;;
            *.tar.lrz) lrzuntar "$1" ;;
            *.gz) gunzip -d "$1" ;;
            *.bz2) bunzip2 "$1" ;;
            *.xz) unxz "$1" ;;
            *.lrz) lrunzip "$1" ;;
            *.lz4) lz4 -d "$1" ;;
            *.lzma) unlzma "$1" ;;
            *.z) uncompress "$1" ;;
            *.zip|*.war|*.jar|*.ipa|*.sublime-package|*.ipsw|*.xpi|*.apk|*.aar|*.whl)
                unzip "$1" -d "$extract_dir" ;;
            *.rar) unrar x -ad "$1" ;;
            *.rpm)
                mkdir "$extract_dir"
                cd "$extract_dir" || exit
                rpm2cpio "../$1" | cpio --quiet -id
                cd .. ;;
            *.7z) 7za x "$1" ;;
            *.deb)
                mkdir -p "$extract_dir/control"
                mkdir -p "$extract_dir/data"
                cd "$extract_dir" && ar vx "../$1" >/dev/null
                cd control && tar xzvf ../control.tar.gz
                cd ../data && extract ../data.tar.*
                cd .. && rm -- *.tar.* debian-binary
                cd .. ;;
            *.zst) unzstd "$1" ;;
            *) atool -X "$extract_dir" "$1" || echo "$1 cannot be extracted" ;;
        esac
    else
        printf -- "%s\n" "File doesn't exist"
    fi
else
    printf -- "%s\n" "Usage: ${0##*/} [archive_name]"
fi
