#!/usr/bin/perl

use strict;
use File::Find;
use File::Copy;
use File::stat;
use Getopt::Std;

my %opt;
my $user;
my $server;
my $domain;

getopts('s:u:d:h?',\%opt);

if($opt{h} || $opt{'?'}) {
	print "Usage: $0 -u username -s servername -d domain\n\n";
	exit(1);
}

$opt{u} ? $user = $opt{u}
	: ($user = query_user('User'));

$opt{s} ? $user = $opt{s}
	: ($server = query_user('Server'));

$opt{d} ? $domain = $opt{d}
	: ($server = query_user('Domain'));

find({ wanted => \&process_dir }, './www/htdocs');

sub process_dir {
	my $cur_dir = $File::Find::dir;
	my $file = $_;

	return if (-d $file);

	if($file =~ m/\.html$/i ||
	   $file =~ m/\.htm$/i ||
	   $file =~ m/\.shtml$/i ||
	   $file =~ m/\.shtm$/i ||
	   $file =~ m/\.shtm$/i ||
	   $file =~ m/\.txt$/i ||
	   $file =~ m/\.pl$/i ||
	   $file =~ m/\.cgi$/i) {
		if(check_file($file,$user,$server)) {
			fix_file($file,$user,$server);
		}
	}
}

sub check_file {
	my $infile = shift;
	my $user = shift;
	my $server = shift;
	my $found_ref = 0;

	return(0) if(! -f $infile);

	open(IN,"<$infile") || die "Cannot open $infile: $!";

	while(<IN>) {
		if($_ =~ m/http:\/\/$server\/~$user/i ||
		   $_ =~ m/http:\/\/$server\/%7E$user/i ||
		   $_ =~ m/http:\/\/best.com\/~$user/i ||
		   $_ =~ m/http:\/\/best.com\/%7E$user/i ||
		   $_ =~ m/http:\/\/www.best.com\/~$user/i ||
		   $_ =~ m/http:\/\/www.best.com\/%7E$user/i) {
			$found_ref = 1;
		}
	}

	close(IN);

	return($found_ref);
}

sub fix_file {
	my $infile = shift;
	my $user = shift;
	my $server = shift;
	my $output;
	my $st;
	my $cur_dir = `pwd`;
	chomp($cur_dir);

	$output = `/usr/bin/file $infile`;

	if($output =~ m/executable/i ||
	   $output =~ m/data/i) {
		return;
	}

	print "Fixing: $cur_dir/$infile\n";
	open(IN,"<$infile") || die "Cannot open $infile: $!";
	open(OUT,">$infile.$$") || die "Cannot open $infile.$$: $!";

	while(<IN>) {
		$_ =~ s/http:\/\/$server\/~$user/http:\/\/$domain/i;
		$_ =~ s/http:\/\/$server\/%7E$user/http:\/\/$domain/i;
		$_ =~ s/http:\/\/best\.com\/~$user/http:\/\/$domain/i;
		$_ =~ s/http:\/\/best\.com\/%7E$user/http:\/\/$domain/i;
		$_ =~ s/http:\/\/www\.best\.com\/~$user/http:\/\/$domain/i;
		$_ =~ s/http:\/\/www\.best\.com\/%7E$user/http:\/\/$domain/i;
		print OUT $_;
	}

	close(OUT);
	close(IN);

	$st = stat($infile);

	move($infile,"$infile-before-migration");
	move("$infile.$$",$infile);

	chmod($st->mode,$infile);
}
