#!/usr/bin/perl

if ($#ARGV == 0) {
   # They passed in the serial device
   $Device = $ARGV[0];
}
else {
   $Device = '/dev/ttyS0';
   print "No device given... assuming $Device\n";
}

unless (($Num) = ($Device =~ /\/dev\/ttyS(.)/)) {
   die "Device must be in the form /dev/ttyS?\n";
}

####################################################
# Modify /etc/lilo.conf
####################################################

$SerialLineDone = 0;
$AppendLineDone = 0;
open (LILO,"/etc/lilo.conf");
while ($ThisLine = <LILO>) {
   # If there is already a 'serial=' line, change it...
   if ($ThisLine =~ s/^serial\s*=\s*.*$/serial=$Num,9600n8/) {
      print "Modifying serial line in lilo.conf...\n";
      $SerialLineDone = 1;
   }

   # If there is already an 'append=' line, change it...
   if ($ThisLine =~ s/^append\s*=\s*.*$/append="console=tty0 console=ttyS${Num},9600"/) {
      print "Modifying append line in lilo.conf...\n";
      $AppendLineDone = 1;
   }

   # Store lilo line...
   push @lilo, $ThisLine;

}
close (LILO);

# open /etc/lilo.conf for writing
open (LILO,">/etc/lilo.conf");

# Add serial line if necessary
unless ($SerialLineDone) {
   print "Adding serial line to lilo.conf...\n";
   print LILO "serial=$Num,9600n8\n";
}

# Add append line if necessary
unless ($AppendLineDone) {
   print "Adding append line to lilo.conf...\n";
   print LILO "append=\"console=tty0 console=ttyS${Num},9600\"\n";
}

# Write file...
foreach $ThisLine (@lilo) {
   print LILO $ThisLine;

}
close (LILO);

print "\nWrote /etc/lilo.conf and now running lilo...\n";
system("/sbin/lilo");

####################################################
# Modify /etc/securetty
####################################################

$Found = 0;
open (SEC,"/etc/securetty");
while ($ThisLine = <SEC>) {
   if ($ThisLine =~ /^ttyS${Num}$/) {
      $Found = 1;
   }
   push @Secure, $ThisLine;
}
close (SEC);
unless ($Found) {
   print "Adding ttyS${Num} to /etc/securetty\n";
   push @Secure, "ttyS${Num}\n";
}
open (SEC,">/etc/securetty");
foreach $This (@Secure) {
   print SEC $This;
}
close (SEC);

####################################################
# Modify /etc/inittab
####################################################

$Found = 0;
open (INIT,"/etc/inittab");
while ($ThisLine = <INIT>) {
   if ($ThisLine =~ /ttyS${Num}$/) {
      $Found = 1;
   }
   push @Init, $ThisLine;
}
close (INIT);
unless ($Found) {
   print "Adding ttyS${Num} to /etc/inittab\n";
   push @Init, "c:12345:respawn:/sbin/mingetty ttyS${Num}\n";
}
open (INIT,">/etc/inittab");
foreach $This (@Init) {
   print INIT $This;
}
close (INIT);

