#!/usr/bin/perl
#
# hostname
#
#   This script is a wrapper for the /bin/hostname command on HP-UX
#   to workaround its lack of a "-s" option.
#
#   Additionally, this script performs a verification step so that there
#   is not an accidental setting of the hostname on a system.
#
# ============================================================================
# Modification History
#
# Date      Author                   Comment
# --------  -----------------------  -----------------------------------------
# 20080128  Scott Fafrak             Created.
# 20081119  Scott Fafrak             Added the force option.
#
# ============================================================================
#

use strict;
use Carp;
use English;
use File::Basename;                                         
use Getopt::Long;

$OUTPUT_AUTOFLUSH++;

#
# Operating System Commands
#

my $HOSTNAME = "/bin/hostname";

#
# Variables
#

use constant SUCCESS => 0;
use constant FAILURE => 1;

my $STATUS   = FAILURE;
my $PROMPT   = "no";
my $PROGNAME = basename $0;
my $USAGE    = "
USAGE: $PROGNAME [-h|--help][-s|--short][-f|--force] [newHostname]\n";

#
# Parse the command line
#

my ($help, $short, $force, $host);

GetOptions ("help"  => \$help, 
            "short" => \$short,
            "force" => \$force)
  or die $USAGE;

if ($help || @ARGV > 1) { print $USAGE; exit SUCCESS; }

#
# If we get here we have either a "-s" or we're setting 
# the hostname.
#

if (@ARGV == 1)
{
  die "ERROR: You must be root to set the hostname\n" 
    unless ( $UID == 0 );

  if ($force)
  {
    $PROMPT = "yes";
  }
  else
  {
    print "Are you sure you want change the hostname? (yes|[no]) ";
    chomp ($PROMPT = lc (<STDIN>));
  }
  
  if ($PROMPT =~ /^y/)
  {
    $STATUS = system($HOSTNAME, $ARGV[0]);
      croak "ERROR: $HOSTNAME failed: $?" unless ($STATUS == SUCCESS);
  }
  else
  {
    print "No change will be made\n";
  }
}
else
{
  chomp ($host = qx("$HOSTNAME"));
  
  if ($short)
  {
    $host = (split ('\.', $host))[0];
  }
  
  print "$host\n";
}

exit SUCCESS;