#!/usr/bin/perl

#-----------------------------------------------------------------------------
#
# The chap/pap secrets files needs to be managed a bit better.  PPPoE 
# and PPTP use this file to manage usernames and passwords.  Dialup accounts
# can show up here too.  From now on, each type will be prefixed with a tag.
#
#-----------------------------------------------------------------------------

my $pppoeuser = "";
my $pppoe = "# Webconfig: PPPOE\n";
my $pptp = "# Webconfig: PPTP\n";
my $other = "";

if (-e "/etc/ppp/pppoe.conf") {
	# Cheating with grep
	$pppoeuser = `grep USER= /etc/ppp/pppoe.conf 2>/dev/null`;
	$pppoeuser =~ s/[\"']//g;
	$pppoeuser =~ s/USER=//g;
	chomp($pppoeuser);
}

if (-e "/etc/sysconfig/network-scripts/ifcfg-ppp0") {
	# Cheating with grep
	$pppoeuser = `grep USER= /etc/sysconfig/network-scripts/ifcfg-ppp0 2>/dev/null`;
	$pppoeuser =~ s/[\"']//g;
	$pppoeuser =~ s/USER=//g;
	chomp($pppoeuser);
}

if (-w "/etc/ppp/chap-secrets") {
	open(OLDCHAP, "/etc/ppp/chap-secrets") || exit 1;
	while (<OLDCHAP>) {
		if (/# Webconfig/i) {
			close(OLDCHAP);
			exit 0;
		}
		if (/^#/) {
			$other = $_ 
		} elsif (/$pppoeuser/) {
			$pppoe .= $_ 
		} else {
			my @items = split();
			$pptp .= "$items[0] \"pptp-vpn\" $items[2] $items[3]\n";
		}
	}
}

# create the temp file in /root -- just in case 
open(NEWCHAP, ">/root/chap-secrets.new") || exit 1;
print NEWCHAP $other;
print NEWCHAP $pppoe;
print NEWCHAP $pptp;
close(NEWCHAP);
system("chmod 0600 /root/chap-secrets.new");
system("cp -a /root/chap-secrets.new /etc/ppp/chap-secrets");
system("mv /root/chap-secrets.new /etc/ppp/pap-secrets");
