#!/usr/bin/perl

require 'getopts.pl';
if (!&Getopts ('f') || $opt_h) {
   print $usage;
   exit 1;
}

sub copyfile
{
   my ($from,$to)=@_;
   if (!open(FROM, "< $from")) {
      print STDERR "Can't open $from: $?\n";
      return 0;
   }
   if (!open(TO, "> $to")) {
      print STDERR "Can't open $to: $?\n";
      close(FROM);
      return 0;
   }
   print TO while (<FROM>);
   close(FROM);
   close(TO);
   return 1;
}


foreach $file (@ARGV) {
   my $oldfile = "$file.old";
   my $changed=0;
   if (-f $oldfile) {
      if ($opt_f) {
         unlink($oldfile);
      } else {
	 print STDERR "$file ignored, $oldfile exists\n";
	 next;
      }
    }
    next unless (copyfile($file, $oldfile));
    if (!open(OLD, "< $oldfile")) {
       print STDERR "Can't open $oldfile: $?\n";
       next;
    }
    if (!open(NEW, "> $file")) {
       print STDERR "Can't open $file: $?\n";
       close(OLD);
       rename($oldfile, $file);
       next;
    }
    while (<OLD>) {
       if (/username/) {
	  s/username/user/;
	  $changed=1;
       } elsif (/plugin \/etc\/ppp\/plugins\/(.*)\.so/) {
	  print NEW "-chap\n" if ($1 eq "userpass");
          s/plugin \/etc\/ppp\/plugins\/(.*)\.so/plugin $1.so/;
	  $changed=1;
       }
       print NEW;
    }
    close(NEW);
    close(OLD);
    if ($changed) {
       print "$file changed, backup in $oldfile\n";
    } else {
       unlink($file);
       rename($oldfile, $file);
       print "$file unchanged\n";
    }
}
