#!/usr/bin/perl
## chgacctip
## changes an account to specified IP
## https://confluence.endurance.com/display/HGS/ChgAcctIP 
## Please submit all bug reports to https://jira.endurance.com/browse/HL/ and escalated accordingly
## $Date: 2013-09-10 $
## $Revision: 2.0.2 $
## $Source: http://git.toolbox.hostgator.com/chgacctip $
# (C) 2013 - HostGator.com, LLC

use strict;
use warnings;
use Carp;
use Getopt::Long;
use Term::ANSIColor;
use POSIX qw(strftime);
use Fcntl qw(:flock);
use IPC::Run qw(run);
#use Smart::Comments;
use version; our $VERSION = qv('2.0.2');

# Options

my $user = 'nobody'; # Select User Option
my $ip = '0.0.0.0'; # Select Ip Option
my $oldip; # Original cPanel Assigned IP Address
my $shared_ip = 0; # Set default start of ip type for additional check(s)
my $norebuild; # Select Rebuild Option. Default to No 
my $help; # Help
my $force; # Select Force Option to ignore a portion of ip_validate. Default to No
my $verbose; # Enable Warnings. Default to No.
my @ischroot = ("0",""); # In case we hit a server that is still chrooted for named
my @domains; # Affected List of Domains

# Subs

# sub show_usage;
# sub ip_validate;
# sub user_validate;
# sub check_system;
# sub named_chroot;
# sub norebuild_validate;
# sub get_oldip;
# sub get_userdomains;
# sub check_ssl;
# sub update_named;
# sub update_named_chroot;
# sub update_cpanel_userconfig;
# sub update_cpanel_userdata;
# sub update_cpanel_datacache;
# sub rebuild;


# File Locking (Imported)

# LOCK_SH { 1 } ## shared lock
# LOCK_EX { 2 } ## exclusive lock
# LOCK_NB { 4 } ## non-blocking
# LOCK_UN { 8 } ## unlock


if ( @ARGV < 1 || 
	! GetOptions (
		'user|u=s' => \$user,
		'ip|i=s' => \$ip,
		'force|f' => \$force,
		'norebuild|n' => \$norebuild,
		'verbose|v' => \$verbose,
		'help' => \$help
	) || defined $help ) {
	show_usage();
	exit 2;
}

sub show_usage {

	### Start Show Usage

	print "\nChange Account IP $VERSION\n";
	print "Please report bugs at https://projects.hostgator.com/projects/chgacctip/issues/new\n";
	print "(C) 2013 HostGator.com\n\n";
	print "This script is designed to change an account IP address on a cPanel Server.\n\n";
	printf "\tExample Usage:\t chgacctip --user <Username> --ip <Valid Bound IP>\n";
	printf "\t\t\t chgacctip -u <Username> -i <Valid Bound IP> -f\n\n";
	printf "\t--user\t\t The cPanel User Account to Affect.\n";
	printf "\t--ip\t\t The IP Address to Set.\n";
	printf "\t--force\t\t Do not check if an IP is bound to the server.\tDefault: No\n";
	printf "\t--verbose\t Display warning messages.\tDefault: No\n";
	printf "\t--norebuild\t Disables rebuild of Apache Host Configuration and cPanel Data Caches.\tDefault: No\n";
}

#### Pretty Output

sub error {

	### Start Error

	my $message = shift;
	print "[ ".color("red")."!".color("reset")." ]"." $message\n";
}

sub valid {

	### Start Valid

	my $message = shift;
	print "[ ".color("green")."OK".color("reset")." ]"." $message\n";
}

sub notice {

	### Start Notice

	my $message = shift;
	if ( $verbose ) {
		print "[ ".color("yellow")."WARN".color("reset")." ]"." $message\n";
	}
}

# Validation

sub ip_validate {

	### Start Ip Validation

	# Since we are change IP addresses let's make sure the input is valid.
	# Let's also check that the ip exists on the server unless the override flag is specified.

	my $ip = shift;
	my $ip_invalid = 1;
	
	# Set ip_override.

	if ( $force ) {

		# Option valid set for ease of use later.

		$force = 1;
		$ip_invalid = 0;
		my $message = "IP Validation Override Enabled.";
		notice($message);
	} else {

		# Option valid set for ease of use later.

		$force = 0;
	}

	if ( $ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ and $ip ne "0.0.0.0" and $ip ne "255.255.255") {
		if ( $force == 0 ) {

			### Start iface check

			# Call system tool to load link data, then split the output.
			# We are using some extra steps in here so that we can modify this later for IPv6 if we want to.

			run [ "ip", "a" ], ">", \my $stdout;
			my @bondips;
			my @process = split(/\n/, $stdout);
			chomp(@process);

			foreach my $line (@process) {
				if ( $line =~ /\s+?inet\s+?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ ) {
					my $realip = $1;
					if ( $realip ne '127.0.0.1' ){
						push @bondips, $realip;
					}
        			}
			}
			foreach my $bound ( @bondips ) {
				if ( "$ip" eq "$bound" ) {
					my $message = "IP appears to be Valid and Configured.";
					$ip_invalid = 0;
					valid($message);

					# Now that we have verified that the ip is bonded and routed, let's make sure that it is not reserved.

					if ( -f '/etc/reservedipreasons' ) {
						open my $fh,'<','/etc/reservedipreasons' or croak "Could not open /etc/reservedipreasons\n";
						while ( my $line = <$fh> ) {
							chomp($line);
							my ($rip,$reason) = split(/=/, $line);
							if ( "$ip" eq "$rip" and "$reason" ne "Shared IP" ) {
								my $message = "IP appears to be Reserved!";
								error($message);
								close $fh;
								exit 3;
							}
							if ( "$ip" eq "$rip" and "$reason" eq "Shared IP" ) {
								$shared_ip = 1;
							}
						}
						close $fh;
					}
					last;
				}
			}
		}
	} else {
		my $message = "Invalid IP Formatting Expects xxx.xxx.xxx.xxx";
		error($message);
		exit 3
	}
	if ( $ip_invalid == 1 ) {
		my $message = "Non-routed IP or Not Bonded!";
		error($message);
		exit 3;
	}
	return $shared_ip;
}

sub user_validate {

	### Start User Validation

	# cPanel user accounts are system users. Let's make sure one exists.

	my $user = shift;
	my $user_invalid = 1;
	if ( $user =~ /^\w/ ) {
		open my $fh,'<','/etc/passwd' or croak "Could not open /etc/passwd\n";
		while ( my $line = <$fh> ) {
			my @sys_user = split(/:/, $line);
			if ( "$user" eq "$sys_user[0]" and "$user" ne "nobody" ) {
				my $message = "Valid System user Found.";
				$user_invalid = 0;
				valid($message);
				last;
			}
		}
		close $fh;
	}
	if ( $user_invalid == 1 ) {
		my $message = "No Valid System User.";
		error($message);
		exit 3
	}
}

sub check_system {

	### Start cPanel System Check

	# Ensure we are on a cPanel server.
	
	my $file = '/usr/local/cpanel/startup';
	if ( -f $file ) {
		my $message = "cPanel Found on this server.";
		valid($message);
	} else {
		my $message = "This script will only work on cPanel Servers!";
		error($message);
		exit 3
	}
}

sub named_chroot {

	#### Start Check for Named Chroot

	# Let's make sure that we aren't using named in a chroot. If we are then notify and update
	# the ischoort array so that we can call the right named update sub-routine.

	my $file = '/etc/sysconfig/named';
	open my $fh,'<', $file or croak "Could not open $file\n";
	while ( my $line = <$fh> ) {
		if ( "$line" =~ /^\s+?ROOTDIR/ ) {
			my @row = split(/\"/, $line);
			my $message = "Named is running in a Chroot.";
			@ischroot = ('1', "$row[1]");
			notice($message);
		} 
	}
	close $fh;
	if ( $ischroot[0] == 0 ) {
		my $message = "Named is not running in a Chroot.";
		valid($message);
	}
	return @ischroot;
}

sub norebuild_validate {

	### Validate the Rebuild Status

	# Check to see if rebuild is set to yes. Update variable for easy checking later.

	if ( $norebuild ) {

		# Option valid set for ease of use later

		my $norebuild = 0;
		my $message = "Rebuild Disabled.";
		notice($message);
		return $norebuild;

	} else {

		# Option valid set for ease of user later

		my $norebuild = 1;
		return $norebuild;
	}
}

# Process Request

sub get_oldip {

	### Obtaining the old IP

	# Let's obtain the old IP so that we know what we are looking for during replacements.
	# Though we fully expect to capture this during the file read in, it is still good
	# to have this information available for comparison. We will update the data in the user file
	# in a later sub-routine.

	my $user = shift;
	my $file = "/var/cpanel/users/$user";
	my @oldip;
	if ( -T "$file" ) {
		open my $fh,'<',$file or croak "Could not open $file file\n";
		while ( my $line = <$fh> ) {
			if ( $line =~ /^IP=/ ) {
				@oldip = split("=", $line);
			}
		}
		close $fh;
		chomp(@oldip);
		return $oldip[1];
	}
}

sub get_userdomains {

	### Get the User Domains

	# Let's build our list of affected user domains. So that we can use this data later
	# when we have to update the DNS zones and the cPanel user data.

	my $user = shift;
	my $file = "/var/cpanel/users/$user";
	my @domains;
	if ( -T "$file") {
		open my $fh,'<',$file or croak "Could not open $file file\n";
			while ( my $line = <$fh> ) {
				if ( $line =~ /(?=(^X?DNS\d*=))\S+.?/ ) {
					chomp($line);
					my @row = split(/=/,$line);
					push(@domains,$row[1]);
				}
			}
		close $fh;
		return @domains;
	}
}

sub check_ssl {
	
	### Check Account SSL Status

	# Ensure that we are not moving an SSL enabled account to Shared IP
	
	my $user = shift;
	my $datadir = "/var/cpanel/userdata/$user";

	foreach my $d_t_up ( @domains ) {
		if ( -f "$datadir/$d_t_up" . "_SSL" and $shared_ip == 1 ) {
			my $message = "Shared IP detected while trying to move an SSL enabled account !";
			error($message);
			exit 3
		}
	}
}

sub update_named {

	### Start Updating non-chroot Named

	# Let's generate a new serial number then check if a zone file exists. If the zone exists
	# Open the zone, locate the active serial number and capture it. Then replace the active serial
	# with the new serial. Then check each A record for an ip that matches the old ip on account.
	# Once we match the old ip on account replace it with the new one.

	my $new_serial = strftime( "%Y%m%d%H", localtime( time ) );
	my $changed = 0;

	# Iterate through each domain. Once the zone is open determine if an update should be performed.
	# If no update to the line is required insert it into the output array.
	# If an update is required, perform that update and insert it into the output array.	

	foreach my $d_t_up ( @domains ) {
		if ( -f "/var/named/$d_t_up.db" ) {
			my $found = "$d_t_up found -- working on this zone\n";
			valid($found);
			my @output;
			open my $fh,'<',"/var/named/$d_t_up.db" or croak "Could not open $d_t_up.db";
			while ( my $line = <$fh> ) {
				if ( $line =~ /\s+(\d{10})\s+/) {
					my $serial = $1;
					$line =~ s/$serial/$new_serial/;
				} elsif ( $line =~ /[A]\s+?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ ) {
					my $row = $1;
					if ( $row !~ /127\.0\.0\.1/ and $row = $oldip ) {
						$line =~ s/$oldip/$ip/;
						$changed = 1;
					} else {
						my $message = "Skipping line $. Appears to be a customized record or points to localhost.";
						notice($message);
					}
			}
			chomp($line);
			push @output,$line;
			}
			close $fh;

			# If we detect that we have made a change to the zone then print the output
			# array into a new zone file and close it. Once we close the file move it to the right location.

			if ( $changed ) {
				my $tempfile = "/var/named/$d_t_up.db." . time;
				my $nf = "/var/named/$d_t_up.db";
				open my $tfh,'>',"$tempfile" or croak "Could not open $tempfile";
				flock($tfh,LOCK_EX) or croak "Could not lock $tempfile\n";
				foreach ( @output ) {
					print $tfh "$_\n";
				}
				close $tfh;
				run [ "mv", "$tempfile", "$nf" ];
			}
			my $message = "Zone file for $d_t_up updated.\n";
			valid($message);
		} else {
			my $message = "Zone file could not be found or $d_t_up is a subdomain.\n";
			notice($message);
		}
	}
}

sub update_named_chroot {

	### Start Update chroot Named

	# Let's generate a new serial number then check if a zone file exists. If the zone exists
	# Open the zone, locate the active serial number and capture it. Then replace the active serial
	# with the new serial. Then check each A record for an ip that matches the old ip on account.
	# Once we match the old ip on account replace it with the new one.

	my $new_serial = strftime( "%Y%m%d%H", localtime( time ) );
	my $changed = 0;
	my $datadir = $ischroot[1];

	# Iterate through each domain. Once the zone is open determine if an update should be performed.
	# If no update to the line is required insert it into the output array.
	# If an update is required, perform that update and insert it into the output array.	

	foreach my $d_t_up ( @domains ) {
		if ( -f "$datadir/$d_t_up.db" ) {
			my $found = "$d_t_up found -- working on this zone\n";
			valid($found);
			my @output;
			open my $fh,'<',"$datadir/$d_t_up.db" or croak "Could not open $datadir/$d_t_up.db";
			while ( my $line = <$fh> ) {
				if ( $line =~ /\s+(\d{10})\s+/) {
					my $serial = $1;
					$line =~ s/$serial/$new_serial/;
				} elsif ( $line =~ /[A]\s+?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ ) {
					my $row = $1;
					if ( $row !~ /127\.0\.0\.1/ and $row = $oldip ) {
						$line =~ s/$oldip/$ip/;
						$changed = 1;
					} else {
						my $message = "Skipping line $. Appears to be a customized record or points to localhost.";
						notice($message);
					}
			}
			chomp($line);
			push @output,$line;
			}
			close $fh;

			# If we detect that we have made a change to the zone then print the output
			# array into a new zone file and close it. Once we close the file move it to the right location.

			if ( $changed ) {
				my $tempfile = "$datadir/$d_t_up.db." . time;
				my $nf = "$datadir/$d_t_up.db";
				open my $tfh,'>',"$tempfile" or croak "Could not open $tempfile";
				flock($tfh,LOCK_EX) or croak "Could not lock $tempfile";
				foreach (@output) {
					print $tfh "$_\n";
				}
				close $tfh;
				run [ "mv", "$tempfile", "$nf" ];
			}
			my $message = "Zone file for $d_t_up updated.\n";
			valid($message);
		} else {
			my $message = "Zone file could not be found or $d_t_up is a subdomain.\n";
			notice($message);
		}
	}
}

sub update_cpanel_userconfig {

	### Update Cpanel user Configuration

	# Now that we have updated the DNS zone data it is time to start updating the cpanel user data
	# so that we can initate an apache configuration rebuild. 	

	my $user = shift;
	my $file = "/var/cpanel/users/$user";
	my $new_mtime = time;
	my $changed = 0;

	# Iterate through each entry. Once we identify the affected line we should
	# determine if an update should be performed.
	# If no update to the line is required insert it into the output array.
	# If an update is required, perform that update and insert it into the output array.	

	my @output;

	if ( -T "$file") {
		open my $fh,'<',$file or croak "Could not open $file file\n";
			while ( my $line = <$fh> ) {
				if ( $line =~ /(?=(^IP=))(\S+?)/ ) {
					$line =~ s/$oldip/$ip/;
				}
				if ( $line =~ /^MTIME=(\S+.?)/ ) {
					my $old_mtime = $1;
					$line =~ s/$old_mtime/$new_mtime/;
					$changed = 1;
				}
			chomp($line);
			push @output,$line;
			}
		close $fh;

		# If we detect that we have made a change to the user config then print the output
		# array into the zone file and close it.

		if ( $changed ) {
			my $tempfile = $file . "." . time;
			open my $tfh,'>',"$tempfile" or croak "Could not open $tempfile";
			flock($tfh,LOCK_EX) or croak "Could not lock $tempfile";
			foreach ( @output ) {
				print $tfh "$_\n";
			}
			close $tfh;
			run [ "mv", "$tempfile", "$file" ];
		}
		my $message = "cPanel user configuration for $user updated.\n";
		valid($message);
	} else {
		my $message = "cPanel user configuration for $user could not be updated!\n";
		error($message);
	}
}

sub update_cpanel_userdata {

	### Update cPanel User Data Cache

	# Now that we have updated the user configuration it is time to  start
	# updating the cpanel user data so that we can initate an apache configuration rebuild. 	

	my $user = shift;
	my $changed = 0;
	my $datadir = "/var/cpanel/userdata/$user";

	# Iterate through each entry. Once we identify the affected line we should
	# determine if an update should be performed.
	# If no update to the line is required insert it into the output array.
	# If an update is required, perform that update and insert it into the output array.

	# Start with non-ssl. Then check for SSL and update those.

	foreach my $d_t_up ( @domains ) {
		if ( -f "$datadir/$d_t_up" ) {
			my $found = "$d_t_up found -- working on this data cache.";
			valid($found);
			my @output;
			open my $fh,'<',"$datadir/$d_t_up" or croak "Could not open $datadir/$d_t_up";
			while ( my $line = <$fh> ) {
				if ( $line =~ /ip:\s+?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ ) {
					my $row = $1;
					if ( $row !~ /127\.0\.0\.1/ and $row = $oldip ) {
						$line =~ s/$oldip/$ip/;
						$changed = 1;
					}
				}
			chomp($line);
			push @output,$line;
			}
			close $fh;

			# If we detect that we have made a change to the file then print the output
			# array into the zone file and close it.

			if ( $changed ) {
				my $tempfile = "$datadir/$d_t_up." . time;
				my $nf = "$datadir/$d_t_up";
				open my $tfh,'>',"$tempfile" or croak "Could not open $tempfile";
				flock($tfh,LOCK_EX) or croak "Could not lock $tempfile\n";
				foreach(@output) {
					print $tfh "$_\n";
				}
			close $tfh;
			run [ "mv", "$tempfile", "$nf" ];
			}
			my $message = "cPanel user data updated for $d_t_up\n";
			valid($message);
		}
	}

	# Update SSL Data files that we find.
	# Wipe Changed for SSL Case.

	$changed = 0;

	foreach my $d_t_up ( @domains ) {
		if ( -f "$datadir/$d_t_up" . "_SSL" ) {
			my $found = "$d_t_up found -- working on this SSL data cache.";
			valid($found);
			my @output;
			open my $fh,'<',"$datadir/$d_t_up" . "_SSL" or croak "Could not open $d_t_up" . "_SSL";
			while ( my $line = <$fh> ) {
				if ( $line =~ /^ip:\s+?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ ) {
					my $row = $1;
					if ( $row !~ /127\.0\.0\.1/ and $row = $oldip ) {
						$line =~ s/$oldip/$ip/;
						$changed = 1;
					}
				}
			chomp($line);
			push @output,$line;
			}
			close $fh;

			# If we detect that we have made a change to the file  then print the output
			# array into the zone file and close it.

			if ($changed) {
				my $tempfile = "$datadir/$d_t_up" . "_SSL" . time;
				my $nf = "$datadir/$d_t_up" . "_SSL";
				open my $tfh,'>',"$tempfile" or croak "Could not open $tempfile";
				flock($tfh,LOCK_EX) or croak "Could not lock $tempfile\n";
				foreach (@output) {
					print $tfh "$_\n";
				}
			close $tfh;
			}
			my $message = "cPanel user SSL data updated for $d_t_up" . "_SSL\n";
			valid($message);
		}
	}
}

sub update_cpanel_datacache {

	### Update cPanel Domain Data Cache

	# Now that we have updated the user configuration and data it is time to
	# updating the cpanel user data cache so that we can initate cpanel maintence. 	

	my $user = shift;
	my $changed = 0;
	my $datadir = "/etc";

	# Iterate through each entry. Once we identify the affected line we should
	# determine if an update should be performed.
	# If no update to the line is required insert it into the output array.
	# If an update is required, perform that update and insert it into the output array.

	my @output;

	if ( -f "$datadir/userdatadomains" ) {
		my $found = "User Data Cache found -- working on this Data cache.";
		valid($found);
		open my $fh,'<',"$datadir/userdatadomains" or croak "Could not open $datadir/userdatadomains";
		while ( my $line = <$fh> ) {
			my $match = ": " . $user . "==";
			if ($line =~ /$match/) {
				$line =~ s/$oldip/$ip/;
				$changed = 1;
			}
		chomp($line);
		push @output,$line;
		}
		close $fh;

      		# If we detect that we have made a change to the file  then print the output
		# array into the zone file and close it.

		$changed = 1;

		if ( $changed ) {
			my $tempfile = "$datadir/userdatadomains." . time;
			my $nf = "$datadir/userdatadomains";
			open my $tfh,'>',"$tempfile" or croak "Could not open $tempfile\n";
			flock($tfh,LOCK_EX) or croak "Could not lock $tempfile\n";
			foreach ( @output ) {
				print $tfh "$_\n";
			}
			close $tfh;
			run [ "mv", "$tempfile", "$nf" ];

			my $message = "cPanel data Cache updated.\n";
			valid($message);
		} else {
			my $message = "cPanel data Cache could not be updated.\n";
			notice($message);
		}
	}
}

sub rebuild_system {

	### Start cPanel and System Maintanence

	# Update userdata caches using the cpanel service to ensure that cPanel sees the changes.
	# Update user domains to ensure that additional caches are updated correctly.
	# Reload Bind
	# Rebuild the apache configuration.
	# Gracefully restart apache.

	my $message = "Preparing to perform cPanel and System maintanence";
	notice($message);

	run [ "/scripts/updateuserdatacache", "--force" ];
	run [ "/scripts/updateuserdomains" ];
	my $datacache_u = "cPanel informed of data cache and user configuration updates.";
	valid($datacache_u);	

	my $named_u = "Reloading named configuration.\n";
	valid($named_u);
	run [ "rndc", "reload" ];

	my $rebuild_apache = "Rebuilding httpd.conf.\n";
	valid($rebuild_apache);
	run [ "/scripts/rebuildhttpdconf" ];

	my $restart_apache = "Restarting apache.\n";
	valid($restart_apache);
	run [ "/etc/init.d/httpd", "graceful" ];
}

#### Clean up Inputs.

chomp($ip);
chomp($user);

#### Validate Inputs.

ip_validate($ip);
user_validate($user);
check_system();
@ischroot = named_chroot(@ischroot);

#### Start Processing Request Now that System is Sane.

$oldip = get_oldip($user);

# We don't need to change an account IP if it is already assigned.
# If this is for an IP address mismatch we should use ipfix instead.

if ( $ip eq $oldip ) {
	my $message = "Account is already assigned to $ip\n";
	error($message);
	if ( -f '/root/bin/ipfix' ) {
		my $message1 = "ipfix tool found. Calling it instead\n";
		valid($message1);
		run [ "/root/bin/ipfix", "$user" ];
		exit 3
	} else {
		my $message2 = "If this is for an IP address mismatch use ipfix instead. (ipfix was not found)\n";
		error($message2);
		exit 3
	}
}

$norebuild = norebuild_validate($norebuild);

### Build out list of affected domains.

@domains = get_userdomains($user);

### Ensure User is not being moved to Shared IP with SSL

check_ssl($user,$shared_ip);

### Update DNS Data

if ( $ischroot[0] == 1 ) {
	update_named_chroot();
} else {
	update_named();
}

### Update cPanel Configurations

update_cpanel_userconfig($user,$oldip,$ip);
update_cpanel_userdata($user,$oldip,$ip);
update_cpanel_datacache($user,$oldip,$ip);

if ( $norebuild ) {
	rebuild_system();
}

### print "$user\n";
### print "$oldip\n";
### print "$ip\n";
### print "@domains\n";

__END__
