#!/usr/bin/perl -w
use strict;

#
#  APRS configuration
#

#
#  Read value from the command line and validate
#
sub ReadLine
{
   my ($txt,$val,$def) = @_;
   my $res = '';
   while (length($res)==0)
   {
      if ($def)
      {
         print "Enter $txt: [Default $def]\n";
      }
      else
      {
         print "Enter $txt:\n";
      }
      $res = <>;
      chomp $res;
      $res =~ s/^\s*//;
      $res =~ s/\s*$//;
      length($res)==0 && $def && ($res = $def);
      $val && ($res !~ /$val/) && (print "\nInvalid Entry\n\n") && ($res = '');
   }
   return $res;
}

#
#  Write line to config file
#
sub WriteLine
{
   my ($cmd,$rem) = @_;
   if ($rem)
   {
      printf CFG "%-36s ; %s\n" , $cmd , $rem;
   }
   else
   {
      print CFG "$cmd\n";
   }
}

#
#  APRS passcode for iGate
#
sub PassCode
{
   my ($call) = @_; 
   $call =~ s/-.*$//;
   my @call = map {uc $_} split('',$call);
   my $hash = 0x73e2; 
   # hash callsign two bytes at a time 
   while (@call>0)
   { 
      $hash ^= ord(shift @call)<<8; 
      @call && ($hash ^= ord(shift @call)); 
   } 
   # mask off the high bit so number is always positive 
   return $hash & 0x7fff; 
}

#
#  Get parameters from command line
#
my $call = ReadLine('Node Callsign (e.g. K0NTS [no -1 or -10])','^[A-Za-z]+[0-9]+[A-Za-z]+$');
my $ssid = ReadLine('APRS SSID (e.g. 11])','^[0-9]+$');
my $port = ReadLine('BPQ Port (e.g. 1)','^[1-9]+$');
my $stat = ReadLine('Status Message (used in broadcast)');
my $lat  = ReadLine('Latitude (ddmm.mm[NS])','^[1-9][0-9][0-9][0-9]\.[0-9][0-9][NS]$');
my $lon  = ReadLine('Longitude (dddmm.mm[EW])','^[0-9][0-9][0-9][0-9][0-9]\.[0-9][0-9][EW]$');
my $pass = PassCode($call);

#  Write configuration file
open(CFG , '>aprs.cfg') || die "Cannot open file aprs.cfg\n";
WriteLine("APRSDIGI");
WriteLine("   APRSCALL=$call-$ssid",'APRS callsign');
WriteLine("   APRSPATH $port=APRS,WIDE1-1,WIDE2-1",'APRS port and mode');
WriteLine("   STATUSMSG=$stat",'APRS status message');
WriteLine("   SYMSET=B",'APRS symbol set');
WriteLine("   SYMBOL=a",'APRS icon');
WriteLine("   LAT=$lat",'Latitude (ddmm.mmN/S)');
WriteLine("   LON=$lon",'Longitude (dddmm.mmE/W)');
WriteLine("   BeaconInterval=30",'Beacon interval (minutes)');
WriteLine("   TraceCalls=WIDE,TRACE",'Calls for CALLN-n Processing with Trace');
WriteLine("   FloodCalls=USA",'Calls for CALLN-n Processing without Trace');
WriteLine("   DigiCalls=$call",'Calls for Normal (ie no SSID manipulation) Digi');
WriteLine("   MaxTraceHops=2",'Max value of n in CALLN-n processing.');
WriteLine("   MaxFloodHops=2",'Max value of n in CALLN-n processing.');
WriteLine("   ISHost=noam.aprs2.net",'APRS-IS host name');
WriteLine("   ISPort=14580",'Normal port for a filtered feed');
WriteLine("   ISPasscode=$pass",'Passcode for APRS callsign');
WriteLine("***");
close(CFG);
