#!/usr/pkg/bin/perl -w
use strict;

# $Id: shell-quote,v 1.3 2010-06-11 20:00:24 roderick Exp $
#
# Roderick Schertler <roderick@argon.org>

# Copyright (C) 1999 Roderick Schertler
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# For a copy of the GNU General Public License write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

use String::ShellQuote	qw(shell_quote);

(my $Me		= $0 ne '-e' ? $0 : $^X) =~ s-.*/--;
my $Debug	= 0;
my $Exit	= 0;
my $Version	= q$Revision: 1.3 $ =~ /(\d\S+)/ ? $1 : '?';

my @Option_spec = (
    'debug!'	=> \$Debug,
    'help!'	=> sub { usage() },
    'version'	=> sub { print "$Me version $Version\n"; exit },
);

my $Usage = <<EOF;
usage: $Me [switch]...
switches:
    --debug	turn debugging on
    --help	show this and then die
    --version	show the version ($Version) and exit
Use \`perldoc $Me\' to see the full documentation.
EOF

sub debug {
    print STDERR "debug: ", @_, "\n" if $Debug;
}

sub usage {
    warn "$Me: ", @_ if @_;
    # Use exit() rather than die(), as Getopt::Long does eval().
    print STDERR $Usage;
    exit 1;
}

# This is basically Getopt::Long but it has the defaults set up the way I
# think they should be.

sub getopt {
    # Don't bother if there aren't any switches.  This test works because
    # I'm setting $REQUIRE_ORDER.
    return 1 unless @ARGV && substr($ARGV[0], 0, 1) eq '-';

    my $bundling = 0;
    if (@_ && ($_[0] eq -bundle || $_[0] eq -bundling)) {
	$bundling = 1;
	shift;
    }

    {
	# I'm setting this environment variable when loading Getopt::Long
	# so that the defaults for options added later (which aren't set
	# explicitly below) are more likely to match what I'd like.
	local $ENV{POSIXLY_CORRECT} = 1;
	require Getopt::Long;
    }

    Getopt::Long->VERSION(2.19);
    Getopt::Long::Configure(
	'no_auto_abbrev',
	'no_getopt_compat',
	'require_order',
	$bundling ? 'bundling' : (),
	'no_ignore_case',
	'prefix_pattern=(--|-)',
    ) if 1;

    # The getopt function puts the vars into its caller's package so
    # it's necessary to jump to it so that its caller is my caller.
    #goto &Getopt::Long::GetOptions;
    Getopt::Long::GetOptions(@_);
}

sub init {
    getopt -bundle, @Option_spec or usage if @ARGV;
}

sub main {
    init;
    print shell_quote(@ARGV), "\n"
	if @ARGV;
    return 0;
}

$Exit = main || $Exit;
$Exit = 1 if $Exit && !($Exit % 256);
exit $Exit;

__END__

=head1 NAME

shell-quote - quote arguments for safe use, unmodified in a shell command

=head1 SYNOPSIS

B<shell-quote> [I<switch>]... I<arg>...

=head1 DESCRIPTION

B<shell-quote> lets you pass arbitrary strings through the shell so that
they won't be changed by the shell.  This lets you process commands or
files with embedded white space or shell globbing characters safely.
Here are a few examples.

=head1 EXAMPLES

=over

=item B<ssh preserving args>

When running a remote command with ssh, ssh doesn't preserve the separate
arguments it receives.  It just joins them with spaces and passes them to
C<$SHELL -c>.  This doesn't work as intended:

    ssh host touch 'hi there'		# fails

It creates 2 files, F<hi> and F<there>.  Instead, do this:

    cmd=`shell-quote touch 'hi there'`
    ssh host "$cmd"

This gives you just 1 file, F<hi there>.

=item B<process find output>

It's not ordinarily possible to process an arbitrary list of files
output by B<find> with a shell script.  Anything you put in $IFS to
split up the output could legitimately be in a file's name.  Here's how
you can do it using B<shell-quote>:

    eval set -- `find -type f -print0 | xargs -0 shell-quote --`

=item B<debug shell scripts>

B<shell-quote> is better than B<echo> for debugging shell scripts.

    debug() {
    	[ -z "$debug" ] || shell-quote "debug:" "$@"
    }

With B<echo> you can't tell the difference between C<debug 'foo bar'>
and C<debug foo bar>, but with B<shell-quote> you can.

=item B<save a command for later>

B<shell-quote> can be used to build up a shell command to run later.
Say you want the user to be able to give you switches for a command
you're going to run.  If you don't want the switches to be re-evaluated
by the shell (which is usually a good idea, else there are things the
user can't pass through), you can do something like this:

    user_switches=
    while [ $# != 0 ]
    do
    	case x$1 in
    	    x--pass-through)
	    	[ $# -gt 1 ] || die "need an argument for $1"
	    	user_switches="$user_switches "`shell-quote -- "$2"`
    	    	shift;;
    	    # process other switches
    	esac
    	shift
    done
    # later
    eval "shell-quote some-command $user_switches my args"

=back

=head1 OPTIONS

=over 4

=item B<--debug>

Turn debugging on.

=item B<--help>

Show the usage message and die.

=item B<--version>

Show the version number and exit.

=back

=head1 AVAILABILITY

The code is licensed under the GNU GPL.  Check
http://www.argon.org/~roderick/ or CPAN for updated versions.

=head1 AUTHOR

Roderick Schertler <roderick@argon.org>

=cut
