#!/usr/bin/perl

# remove old link

unlink ("/etc/alternatives/sudo") if ( -l "/etc/alternatives/sudo");

# make sure we have a sudoers file
if ( ! -f "/etc/sudoers") {

	print "No /etc/sudoers found... creating one for you.\n";

	open (SUDOERS, "> /etc/sudoers");
	print SUDOERS "# /etc/sudoers\n",
	  "#\n",
	  "# This file MUST be edited with the 'visudo' command as root.\n",
	  "#\n",
	  "# See the man page for details on how to write a sudoers file.\n",
	  "#\n\nDefaults\tenv_reset\n\n",
	  "# Host alias specification\n\n",
	  "# User alias specification\n\n",
	  "# Cmnd alias specification\n\n",
	  "# User privilege specification\nroot\tALL=(ALL) ALL\n\n",
	  "# Allow members of group sudo to execute any command\n",
	  "# (Note that later entries override this, so you might need to move\n",
          "# it further down)\n",
	  "%sudo ALL=(ALL) ALL\n",
	  "#\n",
	  "#includedir /etc/sudoers.d\n";
	close SUDOERS;

}

# handle state directory transition from /var/run/sudo to /var/lib/sudo,
# moving any existing content over to avoid re-lecturing existing users
if ( -d "/var/run/sudo") {
	system ('mkdir -p /var/lib/sudo');
	system ('mv /var/run/sudo/* /var/lib/sudo/');
	system ('rmdir /var/run/sudo');
}

# make sure sudoers has the correct permissions and owner/group
system ('chown root:root /etc/sudoers');
system ('chmod 440 /etc/sudoers');

# must do a remove first to un-do the "bad" links created by previous version
system ('update-rc.d -f sudo remove >/dev/null 2>&1');

system ('update-rc.d sudo start 75 2 3 4 5 . >/dev/null');

# make sure we have a sudo group

exit 0 if getgrnam("sudo"); # we're finished if there is a group sudo

$gid = 27;                 # start searcg with gid 27
setgrent;
while (getgrgid($gid)) {
	++$gid;
}
endgrent;

if ($gid != 27) {
	print "On Debian we normally use gid 27 for 'sudo'.\n";
	$gname = getgrgid(27);
	print "However, on your system gid 27 is group '$gname'.\n\n";
	print "Would you like me to stop configuring sudo so that you can change this? [n] "; 
	$ans = <STDIN>;
        if ($ans =~ m/^[yY].*/) {
		print "'dpkg --pending --configure' will restart the configuration.\n\n\n";
		exit 1;
	}
}

print "Creating group 'sudo' with gid = $gid\n";
system("groupadd -g $gid sudo");

print "";
