# GNU tar(1) completion


comp_include _filedir _get_cword


_tar()
{
    local cur ext regex tar untar

    COMPREPLY=()
    cur=`_get_cword`

    if [ $COMP_CWORD -eq 1 ]; then
        COMPREPLY=( $( compgen -W 'c t x u r d A' -- $cur ) )
        return 0
    fi

    case "${COMP_WORDS[1]}" in
    ?(-)c*f)
        _filedir
        return 0
        ;;
    +([^IZzjy])f)
        ext='t@(ar?(.@(Z|gz|bz?(2)))|gz|bz?(2))'
        regex='t\(ar\(\.\(Z\|gz\|bz2\?\)\)\?\|gz\|bz2\?\)'
        ;;
    *[Zz]*f)
        ext='t?(ar.)@(gz|Z)'
        regex='t\(ar\.\)\?\(gz\|Z\)'
        ;;
    *[Ijy]*f)
        ext='t?(ar.)bz?(2)'
        regex='t\(ar\.\)\?bz2\?'
        ;;
    *)
        _filedir
        return 0
        ;;
        
    esac

    if [[ "$COMP_LINE" == *$ext' ' ]]; then
        # complete on files in tar file
        #
        # get name of tar file from command line
        tar=$( echo "$COMP_LINE" | \
            sed -e 's/^.* \([^ ]*'$regex'\) .*$/\1/' )
        # devise how to untar and list it
        untar=t${COMP_WORDS[1]//[^Izjyf]/}

        COMPREPLY=( $( compgen -W "$( echo $( tar $untar $tar \
                2>/dev/null ) )" -- "$cur" ) )
        return 0
    fi

    # file completion on relevant files
    _filedir $ext

    return 0
} # _tar()
