#!/usr/bin/perl -w
# NAME: replacetxt.pl
# AIM: Given an input file, a text string to find, and a text string to replace it with,
# and an OUPUT file to write.
# 19/05/2012 geoff mclane http://geoffair.net/mperl
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Cwd;
my $os = $^O;
my $perl_dir = '/home/geoff/bin';
my $PATH_SEP = '/';
my $temp_dir = '/tmp';
if ($os =~ /win/i) {
    $perl_dir = 'C:\GTools\perl';
    $temp_dir = $perl_dir;
    $PATH_SEP = "\\";
}
unshift(@INC, $perl_dir);
require 'lib_utils.pl' or die "Unable to load 'lib_utils.pl' Check paths in \@INC...\n";
# log file stuff
our ($LF);
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $temp_dir.$PATH_SEP."temp.$pgmname.txt";
open_log($outfile);

# user variables
my $VERS = "0.0.1 2012-05-19";
my $load_log = 0;
my $in_file = '';
my $in_find = '';
my $in_replace = '';
my $out_file = '';
my @in_files = ();

my $verbosity = 0;
my $debug_on = 0;
my $def_file = 'def_file';

### program variables
my @warnings = ();
my $cwd = cwd();
my %dupe_lines = ();
my $total_lines = 0;

sub VERB1() { return $verbosity >= 1; }
sub VERB2() { return $verbosity >= 2; }
sub VERB5() { return $verbosity >= 5; }
sub VERB9() { return $verbosity >= 9; }

sub show_warnings($) {
    my ($val) = @_;
    if (@warnings) {
        prt( "\nGot ".scalar @warnings." WARNINGS...\n" );
        foreach my $itm (@warnings) {
           prt("$itm\n");
        }
        prt("\n");
    } else {
        prt( "\nNo warnings issued.\n\n" ) if (VERB9());
    }
}

sub pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prt($msg);
    }
    show_warnings($val);
    close_log($outfile,$load_log);
    exit($val);
}


sub prtw($) {
   my ($tx) = shift;
   $tx =~ s/\n$//;
   prt("$tx\n");
   push(@warnings,$tx);
}

# \ ^ $ . | { } [ ] ( ) * + ? /
sub escape_text($) {
    my $txt = shift;
    $txt =~ s/\\/\\\\/g;
    $txt =~ s/\^/\\\^/g;
    $txt =~ s/\$/\\\$/g;
    $txt =~ s/\./\\\./g;
    $txt =~ s/\|/\\\|/g;
    $txt =~ s/\{/\\\{/g;
    $txt =~ s/\}/\\\}/g;
    $txt =~ s/\[/\\\[/g;
    $txt =~ s/\]/\\\]/g;
    $txt =~ s/\(/\\\(/g;
    $txt =~ s/\)/\\\)/g;
    $txt =~ s/\*/\\\*/g;
    $txt =~ s/\+/\\\+/g;
    $txt =~ s/\?/\\\?/g;
    $txt =~ s/\//\\\//g;
    return $txt;
}

sub process_in_file($$$) {
    my ($inf,$rlines,$rchg) = @_;
    pgm_exit(1,"ERROR: Unable to open file [$inf]\n") if (! open INF, "<$inf");
    my @lines = <INF>;
    close INF;
    my $lncnt = scalar @lines;
    $total_lines += $lncnt;
    my ($line,$inc,$lnn,$max,$chg,$i,$find,$repl,$oline,$u2d,$d2u);
    $lnn = 0;
    $chg = 0;
    $u2d = 0;
    $d2u = 0;
    if (($in_find eq "/")&&($in_replace eq "\\")) {
        $u2d = 1;
        ###prt("Got UNIX path to DOS path conversion.\n");
    } elsif (($in_find eq "\\")&&($in_replace eq "/")) {
        $d2u = 1;
        ###prt("Got DOS path to UNIX path conversion.\n");
    }
    $find = escape_text($in_find);
    $repl = escape_text($in_replace);
    prt("Processing $lncnt lines, from [$inf]...\n");
    for ($i = 0; $i < $lncnt; $i++) {
        $line = $lines[$i];
        chomp $line;
        $oline = $line;
        $lnn++;
        if ($u2d) {
            $line = path_u2d($line);
            $chg++ if ($oline ne $line);
        } elsif ($$d2u) {
            $line = path_d2u($line);
            $chg++ if ($oline ne $line);
        } elsif ($line =~ /$find/) {
            $line =~ s/$find/$repl/g;
            if ($oline eq $line) {
                prtw("WANRING: $lnn: Line [$line] NOT changed!\n");
            } else {
                prt("$lnn: Changed [$oline] to [$line]\n") if (VERB9());
                $chg++;
            }
        }

        if (!defined $dupe_lines{$line}) {
            $dupe_lines{$line} = 1;
            push(@{$rlines},$line);
        }
    }

    ${$rchg} += $chg;
}

sub process_in_files() {
    my @lines = ();
    my ($file,$chg);
    $chg = 0;
    my $find = escape_text($in_find);
    my $repl = escape_text($in_replace);
    my $fcnt = scalar @in_files;
    prt("Finding [$in_find], and replace it with [$in_replace] in $fcnt file(s)\n");
    prt("Escaped find [$find], and replace with [$repl]\n");
    if (($in_find eq "/")&&($in_replace eq "\\")) {
        ###$u2d = 1;
        prt("Got UNIX path to DOS path conversion.\n");
    } elsif (($in_find eq "\\")&&($in_replace eq "/")) {
        ###$d2u = 1;
        prt("Got DOS path to UNIX path conversion.\n");
    }

    foreach $file (@in_files) {
        process_in_file($file,\@lines,\$chg);
    }
    my $lncnt = scalar @lines;
    if ($chg && $lncnt) {
        my $line = join("\n",@lines)."\n";
        prt("Finding [$in_find], and replace it with [$in_replace]\n");
        prt("Escaped find [$find], and replace with [$repl]\n");
        prt("Result of $lncnt lines of $total_lines, $chg changed, from $fcnt file(s)...\n");
        if (length($out_file)) {
            write2file($line,$out_file);
            prt("Written $lncnt lines to [$out_file]\n");
        } else {
            prt($line);
            prt("No output file given\n");
        }
    } else {
        prt("Found NO lines to write...\n");
    }
}


#########################################
### MAIN ###
parse_args(@ARGV);
process_in_files();
pgm_exit(0,"");
########################################
sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have a following argument!\n") if (!@av);
}

sub parse_args {
    my (@av) = @_;
    my ($arg,$sarg);
    while (@av) {
        $arg = $av[0];
        if ($arg =~ /^-/) {
            $sarg = substr($arg,1);
            $sarg = substr($sarg,1) while ($sarg =~ /^-/);
            if (($sarg =~ /^h/i)||($sarg eq '?')) {
                give_help();
                pgm_exit(0,"Help exit(0)");
            } elsif ($sarg eq 'u2d') {
                $in_find = "/";
                $in_replace = "\\";
                prt("u2d Find [$in_find] and replace with [$in_replace].\n") if (VERB1());
            } elsif ($sarg eq 'd2u') {
                $in_find = "\\";
                $in_replace = "/";
                prt("d2u Find [$in_find] and replace with [$in_replace].\n") if (VERB1());
            } elsif ($sarg =~ /^v/) {
                if ($sarg =~ /^v.*(\d+)$/) {
                    $verbosity = $1;
                } else {
                    while ($sarg =~ /^v/) {
                        $verbosity++;
                        $sarg = substr($sarg,1);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg =~ /^l/) {
                $load_log = 1;
                prt("Set to load log at end.\n") if (VERB1());
            } elsif ($sarg =~ /^f/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $in_find = strip_quotes($sarg);
                prt("Finding [$in_find] text.\n") if (VERB1());

            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if (VERB1());
            } elsif ($sarg =~ /^r/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $in_replace = strip_quotes($sarg);
                prt("Replace with [$in_replace] text.\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! [$sarg] Try -?\n");
            }
        } else {
            $in_file = $arg;
            if (! -f $arg) {
                pgm_exit(1,"ERROR: Unable to locate file [$arg]!\n");
            }
            push(@in_files,$arg);
            prt("Adding input [$in_file]\n") if (VERB1());
        }
        shift @av;
    }

    if ((length($in_file) ==  0) && $debug_on) {
        $in_file = $def_file;
        prt("Set DEFAULT input to [$in_file]\n");
    }
    if (length($in_file) ==  0) {
        pgm_exit(1,"ERROR: No input file found in command!\n");
    }
    if (length($in_find) == 0) {
        pgm_exit(1,"ERROR: No find text found in command!\n");
    }
    if (length($in_replace) == 0) {
        pgm_exit(1,"ERROR: No replacement text found in command!\n");
    }
    if (! -f $in_file) {
        pgm_exit(1,"ERROR: Unable to find in file [$in_file]! Check name, location...\n");
    }
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-file\n");
    prt("Options:\n");
    prt(" --help  (-h or -?) = This help, and exit 0.\n");
    prt(" --verb[n]     (-v) = Bump [or set] verbosity. def=$verbosity\n");
    prt(" --load        (-l) = Load LOG at end. ($outfile)\n");
    prt(" --find txt    (-f) = Text to find.\n");
    prt(" --repl txt    (-r) = Replace found text with this text.\n");
    prt(" --out <file>  (-o) = Write output to this file.\n");
    prt(" SOme 'special' find an replace options.\n");
    prt(" --u2d              = Convert UNIX paths to DOS paths.\n");
    prt(" --d2u              = Convert DOS paths to UNIX paths.\n");
}


# eof - replacetxt.pl
