#!/bin/sh

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/..
    cd ..
    if [ -d 'zxtm/bin' ]
    then
       ZEUSHOME=`pwd`
       export ZEUSHOME
       cd $OLD_PWD
    fi
fi

if [ ! -z "$ZEUSHOME" ]
then
   PROG=$ZEUSHOME/perl/miniperl
fi

exec $PROG -x $0 ${1+"$@"}
#!perl -w
#line 26

# This is called by the Zeus software when a license key changes so
# that the Zeus Appliance can be updated with the new software name


BEGIN { unshift @INC, "$ENV{ZEUSHOME}/zxtm/lib/perl",
     "$ENV{ZEUSHOME}/zxtmadmin/lib/perl", "$ENV{ZEUSHOME}/perl" }

use Zeus::ZXTM::Flavour;
use strict;

sub usage($)
{
   my( $fh ) = @_;
   $fh ||= *STDOUT;

   print $fh "Usage: $0 <license key name>\n\n";
}

if( ! @ARGV ) {
   usage( *STDERR );
   exit 1;
} elsif( grep /^--?h(elp)?$/, @ARGV ) {
   usage( *STDOUT );
   exit 0;
}

# Check the key exists
my $key = shift;
if( $key !~ m|^/| ) {
   $key = "$ENV{ZEUSHOME}/zxtm/conf/licensekeys/$key"
}

# Make sure key exists if keyname doesn't imply Developer Edition
# Mode( Starts with Developer_Mode)
if( ( !$key ) || (( $key !~ /^Developer_Mode/i ) && (! -f $key ))) {
   usage( *STDERR );
   exit 1;
}

# Only do this on the appliance
#exit 0 unless -f "/etc/zxtm-version";

my $newname = Zeus::ZXTM::Flavour::getProductName();

# Load in the old /etc/zxtm-version file
my $file = '';
open FILE, "/etc/zxtm-version" || die "Could not open /etc/zxtm-version: $!\n";
while( <FILE> ) {
   $file .= $_;
}
close FILE;

die "Failed to find existing long name\n"
    unless $file =~ /^PRODUCT_LONG_NAME=(.*)$/m;

my $longname = $1;
$longname =~ s/^"|"$//g;

# Nothing to do
exit 0 if( $newname eq $longname );

# Don't change longname if it isn't "Stingray XXXXX"
exit 0 if $longname !~ /^Stingray/;

# Update the file
$file =~ s/^(PRODUCT_LONG_NAME)=.*$/$1="$newname"/m;
open FILE, ">/etc/zxtm-version";
print FILE $file;
close FILE;

# Need to ensure that grub and the console are right
system( "/usr/bin/killall", "z-doneboot" );
system( "/usr/sbin/update-grub" ) if -f "/boot/grub/menu.lst";

exit 0;
