#!/usr/bin/perl -I/opt/SUNWstade/lib

#<copyright>
# ----------------------------------------------------------
# Sun Proprietary/Confidential Code
# Copyright 2001, Sun Microsystems, Inc. All rights reserved.
# ----------------------------------------------------------
#</copyright>

use Getopt::Std;
use System;
use strict;

use vars qw ($DEBUG %opts $DEBUG_EXT);

$DEBUG = 0;

#-----------------------------------------------------------------------

System->set_home(System->home_dir());

sub usage {
  print <<EOF;
 Usage: changespname -n <hostname>  -?|h [help]

EOF
}

$DEBUG_EXT = ".test" if ($DEBUG);

if (!getopts("n:?h", \%opts) || $opts{'?'} || !$opts{n} || $opts{h}) {
    usage();
    exit(1);
}

my ($err);
my $hostname = $opts{n};

# change the host file

$err = &fix_host_file($hostname);
&print_err($err);

$err = &fix_file("/etc/nodename",       $hostname);
&print_err($err);
$err = &fix_file("/etc/hostname.dmfe0", $hostname);
&print_err($err);

$err = &fix_last_line("/etc/net/ticlts/hosts", $hostname);
&print_err($err);
$err = &fix_last_line("/etc/net/ticots/hosts", $hostname);
&print_err($err);
$err = &fix_last_line("/etc/net/ticotsord/hosts", $hostname);
&print_err($err);

print "Done.\n";


sub fix_last_line {
  my($fname, $hostname) = @_;
  my(@L);
  if (!open(O, $fname)) {
    return "Cannot open $fname: $!";
  }
  @L = <O>;
  close(O);
  if ($#L >= 0) {
    $L[$#L] = "$hostname\t$hostname\n";
  }
  if (open(O, ">$fname$DEBUG_EXT")) {
    print O join("", @L);
    close(O);
  } else {
    return "Cannot write $fname: $!";
  }
  return 0;
}

sub print_err {
  my($err) = @_;
  if ($err) {
     print "Error: $err";
     exit(1);
  }
}

sub fix_file {
  my($fname, $hostname) = @_;

  if (open(O, ">$fname$DEBUG_EXT")) {
    print O  "$hostname\n";
    close(O);
    return 0;
  } else {
    return "Cannot open $fname: $!\n";
  }
}


sub fix_host_file {
  my($hostname) = @_;
  my $FILE = "/etc/hosts";
  open(O, $FILE);
  my ($hfile, $out, $l, $found);
  
  while ($l = <O>) {
    chop($l);
    my ($text, $comment);
    if (substr($l, 0,1) eq "#") {
        $out .= "$l\n";
        next;
    } 
  
    my $ix = index($l, "#");
    if ($ix > 0) {
      $text = substr($l,0,$ix);
      $comment = substr($l, $ix+1);
    } else {
      $text = $l;
    }
    my($ipno, $ip, $alias, $log) = split(/\s+/, $text,4);
    
    if ($hostname eq $alias) {
       $found = 1;
       $log = "loghost";
    } else {
       $log = "";
    }
    $out .= "$ipno\t$ip $alias\t$log";
    $out .= "\t# $comment" if ($comment);
    $out .= "\n";
  }
  
  close(O);
  
  open(O, ">$FILE$DEBUG_EXT");
  print O $out;
  close(O);
  if (!$found) {
    return "Cannot find '$hostname' in /etc/hosts!\n";
  }
  return 0;
    
}
