#!/usr/bin/perl
# Filename:	every_line
# Author:	David Ljung Madison <DaveSource.com>
# See License:	http://MarginalHacks.com/License
# Description:	Runs a command on every line typed in
use strict;

##################################################
# Setup the variables
##################################################
my $PROGNAME = $0;
$PROGNAME =~ s|.*/||;

##################################################
# Usage
##################################################
sub usage {
  my $msg;
  foreach $msg (@_) { print "ERROR:  $msg\n"; }
  print "\n";
  print "Usage:\t$PROGNAME [-fsvd] <cmd>\n";
  print "\tRuns a command on every input line\n";
  print "\t-f\tForce (keep running on failures)\n";
  print "\t-s\tIgnore empty (whitespace) lines\n";
  print "\n";
  print "\t-v\tSet verbose mode (show commands)\n";
  print "\t-d\tSet debug mode (show commands, don't execute)\n";
  print "\n";
  print "If the command has %s, it will be replaced with the line of input\n";
  print "\n";
  exit -1;
}

sub parse_args {
  my (%opt,@cmd);
  while ($#ARGV>=0) {
    my $arg=shift(@ARGV);
    if ($arg =~ /^-h$/) { usage(); }
    if ($arg =~ /^-f$/) { $opt{force}=1; next; }
    if ($arg =~ /^-s$/) { $opt{empty}=1; next; }
    if ($arg =~ /^-v$/) { $opt{verbose}=1; next; }
    if ($arg =~ /^-d$/) { $opt{debug}=1; next; }
    if ($arg =~ /^-/ && !@cmd) { usage("Unknown option: $arg"); }
    push(@cmd,$arg);
  }
  usage("No command defined") unless @cmd;

  push(@cmd,"%s") unless grep(/\%s/, @cmd);

  (\%opt,@cmd);
}

sub do_cmd {
  my ($opt_H,$str,@cmd) = @_;
  map(s/%s/$str/g, @cmd);
  print "CMD: @cmd\n" if ($opt_H->{verbose} || $opt_H->{debug});
  system(@cmd) unless ($opt_H->{debug});
}

##################################################
# Main code
##################################################
sub main {
  my ($opt_H,@cmd) = parse_args();

  # Do something to the file
  while(<>) {
    chomp;
    next if ($opt_H->{empty} && /^\s*$/);
    do_cmd($opt_H,$_,@cmd);
  }
}
main();
