#!pshcomplete
# gzip compress zcat zmore gunzip uncompress gzcat strip mkdir rmdir chown ln more less cat su nohup exec nice eval trace truss strace sotruss gdb make gmake pmake configure umount mount

sub _make_targets {
    my ($cur, $line, $start, $cmd) = @_;
 
    # if prev argument is -f, return possible filename completions.
    # we could be a little smarter here and return matches against
    # 'makefile Makefile *.mk', whatever exists ##''
    my ($prev) = substr($line, 0, $start) =~ /(\S+)\s+$/;
    if ($prev =~ /^-.*f$/) {
        return compgen('-f', $cur);
    }
 
    # if we want an option, return the possible posix options
    if ($cur eq '-') {
        return qw(-e -f -i -k -n -p -q -r -S -s -t);
    }
 
    # before we scan for targets, see if a makefile name was specified
    # with -f
    my ($makef) = $line =~ /\s+-\S*f\s+(\S+)/;
 
    if (! defined $makef) {
        # make reads 'makefile' before 'Makefile'
        if (-f 'GNUmakefile') {
            $makef = 'GNUmakefile';
        } elsif (-f 'makefile') {
            $makef = 'makefile';
        } elsif (-f 'Makefile') {
            $makef = 'Makefile';
        }
    }
 
    # return empty list unless Makefile exists
    return () unless -f $makef;
 
    open(MAKEFILE, $makef) or (warn("cannot open $makef:$!\n"), return ());
    my @COMPREPLY;
    while (<MAKEFILE>) {
        chomp;
        if (s/\\$//) {
            $_ .= <MAKEFILE>;
            redo;
        }
        if (/^([^#\s][^=:]*):/) {
            push(@COMPREPLY, split(' ', $1)); # multi target
        }
    }
    close(MAKEFILE);
    return @COMPREPLY;
}


complete -f -x '*.gz' gzip
complete -f -x '*.Z' compress
complete -f -x '!*.+(gz|tgz|Gz|Z)' gunzip gzcat zcat zmore
complete -f strip
complete -d mkdir rmdir
complete -f chown ln more cat less
complete -u su
complete -c nohup exec nice eval trace truss strace sotruss gdb
complete -e printenv

complete -F _make_targets -X '+($*|*.[cho])' make gmake pmake

sub _configure_func {
    my ($cur, $line, $start, $cmd) = @_;
 
    return () unless $cur =~ /^-/;
 
    ($cmd) = $line =~ /^\s*(\S+)/;
    return map { chomp, $_ } `"$cmd" --help | awk \'{if (\$1 ~ /--.*/) print \$1}\' | grep ^"$cur" | sort -u`;
}
complete -F _configure_func configure

sub _umount_func {
	open( MOUNT, "mount |");
	my @result=();
	while(<MOUNT>) {
	  push @result, (split(' '))[0];
    }
    close(MOUNT);
    return @result;
}

complete -F _umount_func umount mount
