File: tkpingLib.pm

package info (click to toggle)
tkping 0.1.1-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 392 kB
  • ctags: 71
  • sloc: sh: 2,640; perl: 1,830; makefile: 64
file content (1851 lines) | stat: -rw-r--r-- 55,358 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
package tkpingLib;
###############################################################################
## @(#)FILE: tkpingLib.pm - Perl package of common routines & constants
## @(#)$Source: tkping-0.1.0/tkpingLib.pm $
## ============================================================================
##  Description:
##
##   This file is a repository of generally useful perl-functions.
##   It may be used by including a "use tkpingLib;" statement in your perl 
##   scripts. 
##
###############################################################################

##-----------------------------------------------------------------------------
## IMPORTS:
##  The following variables are expected to be defined in the user's script:
##
##  $main::NAME         = name of your script/program
##  $main::SYNOPSIS    = command-line syntax synopsis
##  $main::ARGUMENTS   = description of all options/arguments
##  $main::DESCRIPTION = brief description (one paragraph) of program
##  $main::opt_debug    = true if '-debug' was specified on the command-line
##  $main::opt_verbose  = true if '-verbose' was specified on the command-line
##  $main::opt_silent   = true if '-silent' was specified on the command-line
##  $main::opt_nodo     = true if '-nodo' was specified on the command-line
##-----------------------------------------------------------------------------

require 5.002;

use vars qw($VERSION @EXPORT @EXPORT_OK);
require Exporter;

@ISA = qw(Exporter);

$VERSION = "1.01";

@EXPORT = qw(
	&VerboseMsg
	&DebugMsg
	&ProgressMsg
	&FatalMsg
	&Msg
	&Usage
	&SetLog
	&EndLog
	&LogMsg
	&RunDate
	&GetDateTime
	&Trim
	&Basename
	&Dirname
	&File2Array
	&Array2Fdesc
	&Array2File
	&ArrayRef2File
    &IniFile2Hash
    &Hash2IniFile
	&BackupFile
	&DoCmd
	&DoCmdRetOutput
	&DoCmdRetSingleLine
	&GeneralMkdir
	&GetUserNames
	&Cmd4thisOsRev
	&EnsureDirExists
	&EnsureVariableExists
	&RequireDir
	&RequireParm
	&Assert
);

@EXPORT_OK = qw(
	$TKPING_LIB_VERSION
	$TKPING_LIB_DATE
	@TKPING_LIB_ABORT_FCN_AR
	$NOTSET_STR
);

##-----------------------------------------------------------------------------
## EXPORTS:
##  The following variables are defined in the user's package by this library:
##
##  $TKPING_LIB_VERSION      = version of tkpingLib library
##  $TKPING_LIB_DATE         = date of creation of this version of clearlib
##
##	@TKPING_LIB_ABORT_FCN_AR = populate this with \&func refs to be executed on exit
##
##  $NOTSET_STR              = common value/name used during option validation
##
##-----------------------------------------------------------------------------
$TKPING_LIB_VERSION            = $VERSION;
$TKPING_LIB_DATE               = "Mon Apr 16 00:11:43 MDT 2001";

@TKPING_LIB_ABORT_FCN_AR = ();

$sep = "-" x 65;

local $unitTestMode=0;
local $traceCalls=0;
local $fatalOccurred=0;
local $logFspec="";
local *LOGFILE;

$NOTSET_STR = "*-NOT-SET-*";


##-----------------------------------------------------------------------------
## FUNCTION:
##   Msg -- display message identified by progname and level of severity
##          to stderr (also logs error messages)
##
## SYNOPSIS:
##   Msg([-nl,|-nonl] [-noid,|-inf,|-war,|-err,] "message text")
##
## EXAMPLE:
##   Msg(-inf,"message text");
##
##      produces: "script: INFO- message text" on STDERR
##
##-----------------------------------------------------------------------------
sub Msg(@)
{
	my @ARGV = @_;
	DebugMsg("Called as: Msg(@ARGV)") if($traceCalls);
	my $ARGC = @ARGV;
	my $prefixText="";
	my $severityText="";
	my $logToo = 0;
	my $noId = 0;
	my $currParm;
	my $optIdx=0;
	my $nuline=1;
	while($ARGC > 0 && $optIdx < $ARGC) {
		for($ARGV[$optIdx]) {
			DebugMsg("Msg(): arg=[$_], optIdx=$optIdx, ARGC=$ARGC") if($traceCalls);
			/^\-.*$/ and do {
				$currParm = $_;
				DebugMsg("Msg(): currParm=[$currParm]") if($traceCalls);
				for($currParm) {
					/^\-nl$/ and do {
						shift @ARGV;
						$prefixText="\n";
						last;
					};
					/^\-nonl$/ and do {
						shift @ARGV;
						$nuline=0;
						last;
					};
					/^\-noid$/ and do {
						shift @ARGV;
						$noId = 1;	# don't display identifier on this message
						last;
					};
					/^\-err$/ and do {
						shift @ARGV;
						$severityText="ERROR- ";
						$logToo = 1;	# force this to be logged
						last;
					};
					/^\-inf$/ and do {
						shift @ARGV;
						$severityText="INFO- ";
						last;
					};
					/^\-war$/ and do {
						shift @ARGV;
						$severityText="WARNING- ";
						last;
					};
					print STDERR "${main::NAME}: WARNING- Msg(): Option [$currParm] not supported!\n";
					shift @ARGV;
				}
				last;
			};
			DebugMsg("Msg(): skipping non-option (++)") if($traceCalls);
			$optIdx++;	# skip this non-option
		}
		$ARGC = @ARGV;
	}
	my ($msgText) = @ARGV;	# text is remainder of list
	
	if( $nuline ) {
		if($noId) {
			print STDERR $msgText,"\n";
		} else {
			print STDERR $prefixText,"${main::NAME}: ",$severityText,$msgText,"\n";
		}
	} else {
		if($noId) {
			print STDERR $msgText;
		} else {
			print STDERR $prefixText,"${main::NAME}: ",$severityText,$msgText;
		}
	}

	if($isLogging && $logToo) {
		if($prefixText ne "") {
			LogMsg(-nl,"$severityText$msgText");
		} else {
			if($noid) {
				LogMsg(-noid,"$msgText");
			} else {
				LogMsg("$severityText$msgText");
			}
		}
	}
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   FatalMsg -- Print the given arguments to STDERR (prefixed by "$NAME: ERROR-").
##  						 and then exit.
##
## SYNOPSIS:
##   &FatalMsg("message text");
##
## SIDE EFFECTS:
##   Exits the script by calling internal routine TerminateExecution().
##
##   produces:	"script: ERROR- message text" on STDERR and exits.
##
##   NOTE: this version also logs if logging is already enabled.
##
##-----------------------------------------------------------------------------
sub FatalMsg(@)
{
	local($_) = @_;
        select(STDERR); $| = 1; select(STDOUT);
	Msg(-nl,-err,"$_");
	if(defined &TerminateExecution) {
		&TerminateExecution(2);
	} else {
		exit(2);
	}
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   ProgressMsg -- display message identified by progname and level of severity
##  				to stdout (also logs error messages)
##
## SYNOPSIS:
##   ProgressMsg([-nl,] [-log,] [-fil {fname},|-filapnd {fname},] "message text")
##
## EXAMPLE:
##   ProgressMsg(-inf,"message text");
##
##   produces:	"script: INFO- message text" on STDOUT
##
##-----------------------------------------------------------------------------
sub ProgressMsg(@)
{
	my @ARGV = @_;
	DebugMsg("Called as: ProgressMsg(@ARGV)") if($traceCalls);
	my $ARGC = @ARGV;
	my $prefixText="";
	my $logToo = 0;
	my $toFileToo = 0;
	my $modeAppend = 0;
	my $noId = 0;
	my $currParm;
	my $outFspec = "";
	my $optIdx=0;
	while($ARGC > 0 && $optIdx < $ARGC) {
		for($ARGV[$optIdx]) {
			DebugMsg("ProgressMsg(): arg=[$_], optIdx=$optIdx, ARGC=$ARGC") if($traceCalls);
			/^\-.*$/ and do {
				$currParm = $_;
				DebugMsg("ProgressMsg(): currParm=[$currParm]") if($traceCalls);
				for($currParm) {
					/^\-nl$/ and do {
						shift @ARGV;
						$prefixText="\n";
						last;
					};
					/^\-noid$/ and do {
						shift @ARGV;
						$noId = 1;	# don't display identifier on this message
						last;
					};
					/^\-log$/ and do {
						shift @ARGV;
						$logToo = 1;	# force this to be logged
						last;
					};
					/^\-fil$/ and do {
						shift @ARGV;
						$toFileToo = 1;  # force this out to file, too
						$modeAppend = 0; # overwrite!
						if($ARGC >= 2) {
							$outFspec = shift @ARGV;
						} else {
							SwengFatalMsg("CODING-ERROR ProgressMsg(): Option [$currParm] requires fileName");
							$toFileToo=0;
						}
						last;
					};
					/^\-filapnd$/ and do {
						shift @ARGV;
						$toFileToo = 1;  # force this out to file, too
						$modeAppend = 1; # append!
						if($ARGC >= 2) {
							$outFspec = shift @ARGV;
						} else {
							SwengFatalMsg("CODING-ERROR ProgressMsg(): Option [$currParm] requires fileName");
							$toFileToo=0;
						}
						last;
					};
					print STDERR "${main::NAME}: WARNING- ProgressMsg(): Option [$currParm] not supported!\n";
					shift @ARGV;
				}
				last;
			};
			DebugMsg("ProgressMsg(): skipping non-option (++)") if($traceCalls);
			$optIdx++;	# skip this non-option
		}
		$ARGC = @ARGV;
	}
	my ($msgText) = @ARGV;	# text is remainder of list
	
	if(! defined $main::opt_silent) {
		if($noId) {
			print STDOUT $msgText,"\n";
		} else {
			print STDOUT $prefixText,"${main::NAME}: ",$msgText,"\n";
		}
	}
	
	if($isLogging && $logToo) {
		if($prefixText ne "") {
			LogMsg(-nl,"$msgText");
		} else {
			if($noid) {
				LogMsg(-noid,"$msgText");
			} else {
				LogMsg("$msgText");
			}
		}
	}
	
	if($toFileToo) {
		if($modeAppend) {
			open OUTFILE, ">>$outFspec" or 
				SwengFatalMsg("Unable to append to [$outFspec], Aborting!!\007");
				return if(UTFatalOccurred());  # return if under unit-test!
		} else {
			open OUTFILE, ">$outFspec" or 
				SwengFatalMsg("Unable to write to [$outFspec], Aborting!!\007");
				return if(UTFatalOccurred());  # return if under unit-test!
		}
		print OUTFILE $prefixText,"${main::NAME}: ",$msgText,"\n";
		close OUTFILE or 
			SwengFatalMsg("ERROR- Unable to close [$outFspec], Aborting!!\007");
			return if(UTFatalOccurred());  # return if under unit-test!
	}
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   VerboseMsg -- Print verbose output. Prints the specified arguments to STDERR
##  						only if '-verbose' was specified on the command-line.
##
## SYNOPSIS:
##   &VerboseMsg("verbose message text");
##
##  		produces:  script(VERBOSE): verbose message text
##
##-----------------------------------------------------------------------------
sub VerboseMsg(@)
{
	print STDERR "${main::NAME}(VERBOSE): @_\n" if ($main::opt_verbose);
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   DebugMsg -- Print debugging output. Prints the specified arguments to
##               STDERR only if '-debug' was specified on the command-line.
##
## SYNOPSIS:
##   DebugMsg("debug message text");
##
##     produces:  script(DBG): debug message text
##
##-----------------------------------------------------------------------------
sub DebugMsg(@)
{
	print STDERR "${main::NAME}(DBG): @_\n" if ($main::opt_debug);
}


##-----------------------------------------------------------------------------
## FUNCTION: 
##   SwengFatalMsg -- Print the given arguments to STDERR (prefixed by "$NAME: ").
##  				  and then exit.
##
##   ****** USED IN THIS PACKAGE ONLY--  real one provided earlier in this file! *****
##  		   (this version supports unit testing for this package!)
##-----------------------------------------------------------------------------
sub SwengFatalMsg(@)
{
	local($_) = @_;
	print STDERR "${main::NAME}: ERROR- $_, Aborting...\n";
	if(not $unitTestMode) {
			exit(2);
	} else {
		$fatalOccurred=1;
	}
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   TerminateExecution -- Perform any desired cleanup actions and exit.
##
## SYNOPSIS:
##   &TerminateExecution($exit_status);
##
## ARGUMENTS:
##   $exit_status: value to pass to exit() when exiting the script
##
## PRECONDITIONS:
##   The global list @TKPING_LIB_ABORT_FCN_AR should contain the name of 
##   zero or morecleanup functions to invoke before exiting the script. 
##   This list isinitially empty, but may be populated by the user if
##   so desired.
##
## SIDE EFFECTS:
##   - Invokes the functions named in @TKPING_LIB_ABORT_FCN_AR. The functions
##     are invoked in order with an empty argument list.
##   - Exits the script.
##
##-----------------------------------------------------------------------------
sub TerminateExecution($)
{
   my $exit_status = shift;
   local $_;
   for (@TKPING_LIB_ABORT_FCN_AR) {
      eval "&${_}()";  ## call user's cleanup function
   }
   exit($exit_status);  ## make sure we exit if the user didnt.
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   Usage -- Print a Usage message and then exit with the specified exit-code.
##            If the exit-code is > 1, then Usage is terse (synopsis only) and
##            goes to STDERR. Otherwise Usage is verbose and goes to STDOUT.
##
## SYNOPSIS:
##   &Usage($val);
##
## ARGUMENTS:
##   $val : The integer exit-code value to use (defaults to 2).
##
## SIDE EFFECTS:
##   Exits the script.
##
##-----------------------------------------------------------------------------
sub Usage(@)
{
   local($_) = @_;
   $_ = 2 unless (/^\d+$/o);
   select STDERR unless ($_ <= 1);
   print "\nUsage: ${main::SYNOPSIS}\n";
   print "\nArguments:${main::ARGUMENTS}${main::DESCRIPTION}\n" unless ($_ > 1);
   exit($_);
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   LogMsg -- Print debugging output. Prints the specified arguments to
##               log file only if logging is enabled
##
## SYNOPSIS:
##   LogMsg([-nl,|-noid,] "logged message text");
##
##     appends  "script: logged message text"  to log file
##
##-----------------------------------------------------------------------------
sub LogMsg(@)
{
	my @ARGV = @_;
	my $ARGC = @ARGV;
	my $prefixText="";
	my $currParm;
	my $optIdx=0;
	my $noId = 0;
	DebugMsg("Called as: LogMsg(@ARGV)") if($traceCalls);
	if(not $isLogging) {
		SwengFatalMsg("LogMsg(): Logging not started yet!");
		return if(UTFatalOccurred());  # return if under unit-test!
	}
	while($ARGC > 0 && $optIdx < $ARGC) {
		for($ARGV[$optIdx]) {
			DebugMsg("LogMsg: arg=[$_], optIdx=$optIdx, ARGC=$ARGC") if($traceCalls);
			/^\-.*$/ and do {
				$currParm = $_;
				DebugMsg("LogMsg: currParm=[$currParm]") if($traceCalls);
				for($currParm) {
					/^\-nl$/ and do {
						shift @ARGV;
						$prefixText="\n";
						last;
					};
					/^\-noid$/ and do {
						shift @ARGV;
						$noId = 1;	# don't display identifier on this message
						last;
					};
					print STDERR "${main::NAME}: WARNING- LogMsg(): Option [$currParm] not supported!\n";
					shift @ARGV;
				}
				last;
			};
			DebugMsg("LogMsg: skipping non-option (++)") if($traceCalls);
			$optIdx++;	# skip this non-option
		}
		$ARGC = @ARGV;
	}
	my ($msgText) = @ARGV;	# text is remainder of list
	my $timeStamp = RunDate();
	if($noid) {
		# print but leave white space where time-stamp would be (so all lines up)
		print LOGFILE "                  $msgText\n";
	} else {
		print LOGFILE "$prefixText${main::NAME}: $timeStamp $msgText\n";
	}
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   SetLog -- enable logging by registering log filename
##
## SYNOPSIS:
##   DebugMsg("debug message text");
##
##  		produces:  script(DBG): debug message text
##
##-----------------------------------------------------------------------------
sub SetLog($)
{
	my $logFspec = shift;
	DebugMsg("SetLog() Entered--") if($traceCalls);
	if(length($logFspec) < 1) {
		SwengFatalMsg("SetLog(): Log Filename must be provided");
		return if(UTFatalOccurred());  # return if under unit-test!
	}
	if($tkpingLib::isLogging) {
		SwengFatalMsg("SetLog(): Attempt to open log 2nd time, aborted!");
		return if(UTFatalOccurred());  # return if under unit-test!
	}
	open LOGFILE, ">>$logFspec" or 
		SwengFatalMsg("Unable to append to [$logFspec], Aborting!!\007");
		return if(UTFatalOccurred());  # return if under unit-test!
        select(LOGFILE); $| = 1; select(STDOUT);
	$tkpingLib::isLogging=1;	# set active flag!
	$tkpingLib::logFspec = $logFspec;
	LogMsg(-nl,"Running...");
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   EndLog -- disable logging
##
## SYNOPSIS:
##   DebugMsg("debug message text");
##
##  		produces:  script(DBG): debug message text
##
##-----------------------------------------------------------------------------
sub EndLog()
{
	DebugMsg("EndLog() Entered--") if($traceCalls);
	if(!$tkpingLib::isLogging) {
		SwengFatalMsg("Attempt to close log 2nd time, aborted!");
		return if(UTFatalOccurred());  # return if under unit-test!
	}
	LogMsg("Complete.");
	$tkpingLib::isLogging=0;	# set INactive flag!
	close LOGFILE or 
		SwengFatalMsg("ERROR- Unable to close [$tkpingLib::logFspec], Aborting!!\007");
		return if(UTFatalOccurred());  # return if under unit-test!
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   RunDate -- return string identifying date/time of log attempt
##  	 (generate standard date-time for logging:	DDmmmYY-HH:MM:SS)
##
## SYNOPSIS:
##   $timeStamp = &RunDate();
##
##  		produces:  $timeStamp = "25May97-12:04:30"
##
##-----------------------------------------------------------------------------
sub RunDate() 
{
	my $runDateTxt = &GetDateTime( 'DDMMMYY-HH:MM:SS' );
	return $runDateTxt;
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   EnableUnitTest -- set bool identifying we are unit-testing!
##
## SYNOPSIS:
##   tkpingLib::EnableUnitTest();
##
##  		(prevents fatal errors from exiting!)
##
##-----------------------------------------------------------------------------
sub EnableUnitTest() 
{
	$unitTestMode=1;
	$traceCalls=1;
	DebugMsg("tkpingLib:: Enabled unit testing");
	return $unitTestMode;
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   UTFatalOccurred -- return true if unit-test-fatal-error occurred
##
## SYNOPSIS:
##   return if(UTFatalOccurred());
##
##  		(used to force exit under unit-test conditions)
##
##-----------------------------------------------------------------------------
sub UTFatalOccurred() 
{
	if(not $unitTestMode) {
		DebugMsg("UTFatalOccurred() NOT in UT mode...") if($traceCalls);;
		return 0;				 # exit no err if not under unit-test
	}
	DebugMsg("UTFatalOccurred() in UT mode... fatalOccurred=$fatalOccurred") if($traceCalls);;
	my $exitState = $fatalOccurred;  # save actual state
	$fatalOccurred = 0;              # clear if set!
	return $exitState;               # return state
}


##-----------------------------------------------------------
## FUNCTION:
##   GetDateTime -- returns formatted date/time string
##  	 based on input pattern specifier
##
## SYNOPSIS:
##   $dateTimeStr = &GetDateTime( $formatSpec )
##
##  NOTES:
##  	1) pattern matching is 'greedy'; put more-specific matches
##  		 earlier than less-specific ( eg., HH:MM:SS before HH:MM )
##
##  	2) $mon has range (0..11) and $wday has range (0..6)
## 
## ----------------------------------------------------------
sub GetDateTime($)
{
	my $formatSpec  = shift;

	my( @monthNmAr ) = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
	                    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );

	my( @dayNmAr ) = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );

	my $dateTimeResult = "GetDateTime::INVALID_FORMAT_ID";

	my( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) 
			= localtime( time );

	# Workaround Perl bug for Y2K
    if( $year > 99 ) { $year = $year - 100 };
    if( length( $year ) < 2 ) { $year = "0$year"; }

	# ----------------------------------------------------------
	#  'Switch' construct ... create output based on $formatSpec
	# ----------------------------------------------------------
	for( $formatSpec ) 
	{
		/DDMMMYY-HH:MM:SS/ and do 
		{
			$dateTimeResult = sprintf( "%2.2d%3.3s%2.2d-%2.2d:%2.2d:%2.2d",
			                      $mday, $monthNmAr[ $mon ], $year, $hour, $min, $sec );
			last;
		};

		/YYMMDD_HH:MM/ and do
		{
			$dateTimeResult = sprintf( "%02d%02d%02d_%02d:%02d", 
			                      $year, $mon+1, $mday, $hour, $min );
			last;
		};

		/HH:MM:SS/ and do 
		{
			$dateTimeResult = sprintf( "%02d:%02d:%02d", $hour, $min, $sec );
			last;
		};

		/HH:MM/ and do 
		{
			$dateTimeResult = sprintf( "%02d:%02d", $hour, $min );
			last;
		};

		/YYMMDD/ and do 
		{
			$dateTimeResult = sprintf( "%02d%02d%02d", $year, $mon +1, $mday );
			last;
		};

		/DD-MMM-YY/ and do 
		{
			$dateTimeResult = sprintf( "%02d-%03s-%02d", $mday, $monthNmAr[ $mon ], $year );
			last;
		};
		FatalMsg( "GetDateTime(): '$formatSpec' is not currently supported" );
	}
	# ----------------------------------------------------------

	return $dateTimeResult;
}



##-----------------------------------------------------------
## FUNCTION:
##   Trim()  -- remove leading and trailing whitespace from 
##  	 input string
##
## SYNOPSIS:
##   $string = Trim( $string );
##
## ----------------------------------------------------------
sub Trim($)
{
	my $trimmedString  = shift;
	$trimmedString =~ s:^\s+:: ;
	$trimmedString =~ s:\s+$:: ;
	return $trimmedString;
}


##-----------------------------------------------------------
## FUNCTION:
##   Basename()  -- remove directory path 
##                  (& optional suffix) from input pathname
##
## SYNOPSIS:
##   $string = &Basename( $string [, $extStr] );
##
## ----------------------------------------------------------
sub Basename($;$)
{
	my $fileBasename = shift;
	my $extension = shift;
	
	if(!defined $extension) {
		$extension = "";
	} else {
		### prep for use as part of regexp
		$extension =~ s/\./\\\./g;
	}

	if($fileBasename eq "") {
	} elsif($fileBasename eq "/" || $fileBasename eq "\\") {
	} else {
		$fileBasename =~ s:^.*[/\\]::g;
	}
	if($^O =~ /win32/i) {
		###  win32 is case insensative!
		$fileBasename =~ s/$extension$//i if($extension ne "");
	} else {
		$fileBasename =~ s/$extension$// if($extension ne "");
	}
	return $fileBasename;
}


##-----------------------------------------------------------
## FUNCTION:
##   Dirname()	-- remove filename from input pathname
##
## SYNOPSIS:
##   $string = &Dirname( $string );
##
## ----------------------------------------------------------
sub Dirname($)
{
	my $fspec = shift;
	
	my $fileDirname;
	my $fileName;

	foreach ($fspec) {
		# iff only / or \ or . or {emptyString} then ...
		/^[\\\/]$/ || /^\.$/ || /^$/ and do {
			$fileDirname = $fspec;
			$fileName = $fspec;
			last;
		};
		# iff only .. then ...
		/^\.\.$/ and do {
			$fileDirname = ".";
			$fileName = $fspec;
			last;
		};
		# all others, do ...
		($fileName, $fileDirname) = ($fspec =~ m|^(.*)[/\\]([^\\/]+)$|o) ? ($2, $1) : ($fspec, '.');
	}

	return $fileDirname;
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   File2Array -- populate array from named file, failing if file does not exist
##
##	NOTE: removes newlines from each element
##
## SYNOPSIS:
##   @array = &File2Array(filename);
##
##-----------------------------------------------------------------------------
sub File2Array($) 
{
	my $filespec = shift;
	my @newAr = ();
	
	DebugMsg("File2Array() loading array from $filespec");
	
	#  ensure our data file exists and open it
	open AR_SRC_FILE,"<$filespec" or
		FatalMsg("Unable to read [$filespec]: $!, Aborting!!\007");
	
	#  load our data file into the array
	@newAr = <AR_SRC_FILE>;	# grab all lines of file

	#  close our data file
	close AR_SRC_FILE or
		FatalMsg("Unable to close [$filespec]: $!, Aborting!!\007");
	
	#  return our array
	chomp @newAr;	# remove newlines...
	my $lineCt = @newAr;
	DebugMsg("File2Array() returning array of $lineCt element(s)");

	return @newAr;
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   Array2File -- write array to named file, overwriting file if it exists
##                   (use BackupFile() to copy before overwrite)
##
##	NOTE: appends newline to each element as it is written to file
##
## SYNOPSIS:
##   &Array2File(filename,@array);
##
##-----------------------------------------------------------------------------
sub Array2File($@) 
{
	my $filespec = shift;
	my @argAr = @_;
	my $lineCt = @argAr;
	DebugMsg("Array2File() writing array ($lineCt element(s)) to $filespec");
	
	#  ensure our data file exists and open it
	open AR_DST_FILE,">$filespec" or
		FatalMsg("Unable to write to [$filespec]: $!, Aborting!!\007");
	
	#  load our data file into the array
	foreach $ele (@argAr) {
		print AR_DST_FILE $ele,"\n";	# write each element to our file
	}

	#  close our data file
	close AR_DST_FILE or
		FatalMsg("Unable to close [$filespec]: $!, Aborting!!\007");
}


### ===========================================================================
###  File Format Specs for   Hash2IniFile() and IniFile2Hash() routines
### ---------------------------------------------------------------------------
###  SYNTAX:  (pretty simple)
###
###    Comment char is '#'.  Comments can be on a line by themselves or
###      on the right edge of any other lines in the file.
###
###    Comments (comment lines or right edge of lines) are stripped before
###      the file is parsed)
###   
###    Blank lines terminate a list (hash or array), multiples are ignored
###
###    There are two value-set forms:  Hash's and Array's (perl'esq)  They are
###    preceeded by keynames of the form '[{keyname}{suffix}]'.
###
###    The suffix identifies (to the parser) which is being specified:
###     SUFFIX:
###        ~Hs   - is a hash
###        ~Ar   - is an array
###
###    An array (~Ar) is specified in one of two forms: (the presence of a 
###    leading '[' indicates which form to use.)
###    
###    [{keyname}Ar]               # head a value list
###    value one                   #  one value per line
###    value two                   #  one value per line
###      ...etc...                 #  
###    {blank line}                # ends value list
###
###    [{keyname}Ar]               # head a value list
###    [000] = value one           #  one value per line (NOTE leading zeros and fixed width)
###    [001] = value two           #  one value per line
###    [002] = value three         #  one value per line
###     ...etc...                  #  
###    {blank line}                # ends value list
###
###        NOTE: this second array form is what the file would look like if written
###        by the tkpingLib::Hash2Ini() library routine.  This form is accepted 
###        primarily so that the reader-side can read the written form of these files.
###
###    A hash (~Hs) is specified in only one form:
###    
###    [{keyname}Hs]               # head a value list
###    key1 = value one            #  one value per line (NOTE leading zeros and fixed width)
###    key2 = value two            #  one value per line
###    key3 = value three          #  one value per line
###      ...etc...                 # 
###    {blank line}                # ends value list
###    
###  The final feature is that hashs can have simple key-value pairs or may
###   contain key-value pairs that effectively point to other hash's and array's.
###   
###  To point from a hash to a hash:
###     [topHs]
###     childHs = theNamedHs
###     simpleKey = simple Value
###
###     [theNamedHs]
###     anotherKey = another simple value
###
###  To point from a hash to a hash:
###     [topHs]
###     childAr = theNamedAr
###     simpleKey = simple Value
###
###     [theNamedAr]
###     value one
###     value 2
###     value drei
###
###   to recap, there are three key forms for hash's:
###    (1) Simple:   {keyname} = value
###    (2) ptr2Hash  {keyname}Hs = {hashName}   # where hashName must end in an ~Hs suffix
###    (3) ptr2Array {keyname}Ar = {arrayName}  # where arrayName must end in an ~Ar suffix
###
###
###  NOTE: arrays can NOT point to arrays or hashs
###
###  NOTE2:  there is no limit (well, maybe memory on your system? ;-) to the 
###     depth you may cascade these references.
###
###  NOTE3:  the presence of a special hash named 'ConstantsHs' will cause
###          its contents to be preloaded into the current namespace.  This
###          is intended to facilitate coding multiple scripts against a single
###          .ini file by moving the constants from a shared source file to
###          the .ini file which is already shared! -Stephen
###
###  SPECIAL WARNING:  watch out for cycles!  You must break them by by using 
###    simple key names for one of the hash's!!
###
###      - Stephen M. Moraco t590-5714  mailto:stephen@cos.agilent.com
### ===========================================================================

### ----------------------------------------------------------------------------
###  scanForKeys - identify hashes/arrays to be written to .ini file
###
sub scanForKeys($@$)
{
    local $startingKey = shift;
    local *resultAr = shift;
    my $namespace = shift;

    DebugMsg("scanForKeys(): namespace=[$namespace],",
             "startingKey=[$startingKey]");
    if($startingKey =~ /Hs$/) {
        foreach my $key (sort keys %{"${namespace}$startingKey"}) {
            my $value = ${"${namespace}$startingKey"}{$key};
            if($key =~ /Hs$/) {
                if($value ne "") {
                    # make name of hash ref namespace-neutral
                    $value =~ s/^$namespace// if ($value =~ /Hs$/);
                    ###  DebugMsg("Found next hash Key=[$value] to archive");
                    push @resultAr,$value;
                    # recurse
                    scanForKeys($value,\@resultAr,$namespace);
                } else {
                    SwengFatalMsg("$startingKey\{$key\} has NO value, must be symbolic-name of hash");
                    return if (UTFatalOccurred());  # return if under unit-test!
                }
            } elsif($key =~ /Ar$/) {
                if($value ne "") {
                    # make name of array ref namespace-neutral
                    $value =~ s/^$namespace// if ($value =~ /Ar$/);
                    push @resultAr,$value;
                    ###  DebugMsg("Found next array Key=[$value] to archive");
                } else {
                    SwengFatalMsg("$startingKey\{$key\} has NO value, must be symbolic-name of array");
                    return if (UTFatalOccurred());  # return if under unit-test!
                }
            }
        # else it's a scalar -- don't do more
        }
    } elsif($startingKey =~ /Ar$/) {
        # done
    } else {
        SwengFatalMsg("Invalid Starting ini Key [$startingKey], must be hash or array");
        return if (UTFatalOccurred());  # return if under unit-test!
    }
}


### ----------------------------------------------------------------------------
###  genHsArIniFile - find then write hashes/arrays to .ini file
###
sub genHsArIniFile(*$$)
{
    local *HSDUMP_OUT = shift;
    my $fileListHsNm = shift;
    my $namespace = shift;

    local @keyListAr = ();

    push @keyListAr,$fileListHsNm;  #  put top key, then chase to get rest
    scanForKeys($fileListHsNm,\@keyListAr,$namespace);
    
    my $keyListCt = @keyListAr;
    ###  DebugMsg("Save $keyListCt keys to ini file");

    my $arrayCt = 0;
    my $hashCt = 0;
    my $value;

    foreach my $keyName (@keyListAr) {
        print HSDUMP_OUT "# $sep\n";
        print HSDUMP_OUT "#\n";
        print HSDUMP_OUT "[$keyName]\n";
        if($keyName =~ /Hs$/) {
            local *hashRef = \%{"${namespace}$keyName"};
            foreach $subKey (sort keys %hashRef) {
                $value = $hashRef{$subKey};
                if ((($subKey =~ /Hs$/) && ($value =~ /Hs$/)) ||
                    (($subKey =~ /Ar$/) && ($value =~ /Ar$/))) {
                    # if it's a symbolic hash or array ref, make the value
                    # namespace-neutral 
                    $value =~ s/^$namespace//;
                }
                print HSDUMP_OUT "$subKey = $value\n";
            }
            print HSDUMP_OUT "\n";
            $hashCt++;
        } elsif($keyName =~ /Ar$/) {
            my $elemCt = 0;
            for (@{"${namespace}$keyName"}) {
                my $line = sprintf("[%03.3d] = %s",$elemCt++,$_);
                print HSDUMP_OUT "$line\n";
            }
            print HSDUMP_OUT "\n";
            $arrayCt++;
        } else {
            SwengFatalMsg("Attempted save of symbolic reference to $keyName, but NO hash name given (as value)");
            return if (UTFatalOccurred());  # return if under unit-test!
        }
    }
    DebugMsg("genHsArIniFile() hash_count=$hashCt, array_count=$arrayCt, top_key=[$fileListHsNm]");
}


## ----------------------------------------------------------------------------
## FUNCTION:
##   Hash2IniFile -- write hash-system to named file, overwriting file if it exists
##                   (Hint: use BackupFile() to copy before overwrite)
##
##  NOTE: Write file in microsoft .ini format
##
## SYNOPSIS:
##   Hash2IniFile($fileSpec,$topHashName[,$namespace]);
##
## uses main:: if $namespace isn't provided
##
##-----------------------------------------------------------------------------
sub Hash2IniFile($$;$)
{
    my $outFName = shift;
    my $topHashHsNm = shift;
    my $namespace = shift;

    $namespace = "main::" if (!defined $namespace); # default
    # append colons if missing
    $namespace .= "::" if ($namespace !~ /::$/);

    DebugMsg("Hash2IniFile() writing hashes/arrays from \%${namespace}$topHashHsNm to $outFName");
    
    open(HSDUMP_OUT,">$outFName") or
      SwengFatalMsg("Can't open [$outFName] for write: $!");
    return if (UTFatalOccurred());  # return if under unit-test!
    
	my ($realId,$effId) = tkpingLib::GetUserNames();
    my $extraIdStr = ($realId ne $effId) ? sprintf("(as %s)",$effId) : "";    
    
    my $dateTimeStr = tkpingLib::GetDateTime("YYMMDD_HH:MM");

    print HSDUMP_OUT "# $sep\n";
    print HSDUMP_OUT "#         FILE:  $outFName\n";
    print HSDUMP_OUT "#    Namespace:  $namespace\n";
    print HSDUMP_OUT "#   Created by:  $::NAME (Ver $::VERSION) [",
    # also note our own package version 
                     __PACKAGE__, " Ver $TKPING_LIB_VERSION]\n";
    print HSDUMP_OUT "#       Run by:  $realId $extraIdStr\n";
    print HSDUMP_OUT "#           on:  $dateTimeStr\n";
    
    genHsArIniFile(\*HSDUMP_OUT, $topHashHsNm, $namespace);
    
    print HSDUMP_OUT "\n";
    print HSDUMP_OUT "#\n";
    print HSDUMP_OUT "# $sep\n";
    print HSDUMP_OUT "#   End of FILE:  $outFName\n";
    print HSDUMP_OUT "# $sep\n";
    
    close HSDUMP_OUT or
      SwengFatalMsg("Can't close $outFName: $!");
    return if (UTFatalOccurred());  # return if under unit-test!
}


## ----------------------------------------------------------------------------
## FUNCTION:
##   IniFile2Hash -- populate hashes/arrays from named file, 
##                   failing if file does not exist.  It returns the
##                   topLevel hash name (without the namespace prefix)
##
##  NOTE:  constructs complex hashs/arrays in $namespace.  If that parameter isn't
##         provided, uses main::.
##
## SYNOPSIS:
##   $hashNm = IniFile2Hash($fileSpec[,$namespace]);
##
##-----------------------------------------------------------------------------
sub IniFile2Hash($;$)
{
    my $iniFspec = shift;
    my $namespace = shift;

    $namespace = "main::" if (!defined $namespace); # default
    # append colons if missing
    $namespace .= "::" if ($namespace !~ /::$/);

    DebugMsg("IniFile2Hash() loading hashes/arrays from $iniFspec,",
             "namespace=[$namespace]");

    my @iniSourceAr;
    @iniSourceAr = File2Array($iniFspec);

    my $topKeyNm = "";
    my $loadingHash = 0;
    my $LoadingArray = 0;
    my $currAHname = "";
    my $hashCt = 0;
    my $arrayCt = 0;
    my $isLoadingConstants = 0;
    foreach my $line (@iniSourceAr) {
        if($line =~ /^\s*#/) {
            next;   # skip comments!
        }
        $line =~ s/\s+#.*$//;   # remove right edge comments
        if($line =~ /^\[/ && !$loadingHash && !$LoadingArray) {
            # beginning new Key
            my $key = $line;
            $key =~ s/\].*$//;  # remove all after key name
            $key =~ s/^\[//;    # remove left begin-key marker
            if($topKeyNm eq "") {
                $topKeyNm = $key;
            }
            my $isHash = ($key =~ /Hs$/) ? 1 : 0;
            if($isHash) {
                $loadingHash = 1;
                $LoadingArray = 0;
                $hashCt++;
                # WAS: $currAHname = $key;
                $currAHname = "${namespace}$key";
                %{"$currAHname"} = ();  ### init the top level hash!!
                DebugMsg("IniFile2Hash() init'd hash [$currAHname]");
                if($key =~ /^ConstantsHs$/) {
                    $isLoadingConstants = 1;    ### TURN-ON name-space populating mech
                }
           } else {
                $loadingHash = 0;
                $LoadingArray = 1;
                $arrayCt++;
                # WAS: $currAHname = $key;
                $currAHname = "${namespace}$key";
                @{"$currAHname"} = ();  ### init the top level hash!!
                DebugMsg("IniFile2Hash() init'd array [$currAHname]");
            }
            next;
        }
        if($line =~ /^\s*$/) {
            $loadingHash = 0;
            $LoadingArray = 0;
            $isLoadingConstants = 0;    ### TURN-OFF name-space populating mech
            next;
        }
        if($loadingHash) {
            my ($keyName, $keyValue) = split /\s*=\s*/,$line,2;

            ### WAS: ${"main::$currAHname"}{$keyName} = $keyValue;
            if ((($keyName =~ /Hs$/) && ($keyValue =~ /Hs$/)) ||
                (($keyName =~ /Ar$/) && ($keyValue =~ /Ar$/))) {
                # (bug fix) adjust the value to the namespace -- the
                # symbolic names need to be in the right namespace
                $keyValue = "${namespace}$keyValue";
            }
            $$currAHname{$keyName} = $keyValue;
            DebugMsg("$currAHname\{$keyName\}=[$$currAHname{$keyName}]");

            if($isLoadingConstants) {
                if(defined ${"${namespace}$keyName"}) {
                    my $oldValue = ${"${namespace}$keyName"};
                    Msg(-war,"Overwriting \$${namespace}$keyName = [$oldValue] with [$keyValue]");
                }
                ${"${namespace}$keyName"} = $keyValue;
                DebugMsg("Loaded Constant \$${namespace}$keyName = [$keyValue]");
            }
            next;
        } elsif($LoadingArray) {
            my $idx;
            my $value;
            if($line =~ /^\[/) {
                ($idx, $value) = split /\]\s*=\s*/,$line,2;
                $idx =~ s/^\[//;
            } else {
                $line =~ s/\s+#.*$//g;  ## remove comments & white before comments
                $value = $line;
            }

            push @$currAHname,$value;

            next;
        }
        # else
        Msg(-err,"Failed to process [$line]");
    }
    DebugMsg("IniFile2Hash() hash_count=$hashCt, array_count=$arrayCt, top_key=[$topKeyNm]");
    return $topKeyNm;
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   BackupFile -- copy named file to backup (preserve file before change)
##
## SYNOPSIS:
##   &BackupFile(filename,".dat",".BAK");
##          -or-
##   &BackupFile(-force,filename,".dat",".BAK");
##
##-----------------------------------------------------------------------------
sub BackupFile(@) 
{
	my @ARGV = @_;
	DebugMsg("Called as: BackupFile(@ARGV)") if($traceCalls);
	my $ARGC = @ARGV;
	my $optIdx=0;
	$forceOverwrite = 0;
	while($ARGC > 0 && $optIdx < $ARGC) {
		for($ARGV[$optIdx]) {
			DebugMsg("BackupFile(): arg=[$_], optIdx=$optIdx, ARGC=$ARGC") if($traceCalls);
			/^\-.*$/ and do {
				$currParm = $_;
				DebugMsg("BackupFile(): currParm=[$currParm]") if($traceCalls);
				for($currParm) {
					/^\-force$/ and do {
						shift @ARGV;
						$forceOverwrite = 1;
						last;
					};
					print STDERR "${main::NAME}: WARNING- BackupFile(): Option [$currParm] not supported!\n";
					shift @ARGV;
				}
				last;
			};
			DebugMsg("BackupFile(): skipping non-option (++)") if($traceCalls);
			$optIdx++;	# skip this non-option
		}
		$ARGC = @ARGV;
	}
	my ($msgText) = @ARGV;	# text is remainder of list
		
	if($ARGC < 3) {
		FatalMsg("BackupFile(): CODE-ERROR- not enough parms provided\007");
	}
	my $newSuffix = pop @ARGV;
	my $origSuffix = pop @ARGV;
	my $filespec = pop @ARGV;
	
	DebugMsg("filespec=$filespec origSuffix=$origSuffix newSuffix=$newSuffix");
	# NOTE: uses open/close pairs for better messaging when fail occurs
	
	open TEST_NBR1,"<$filespec" or
		FatalMsg("Unable to backup [$filespec]: $!, Aborting!!\007");
	close TEST_NBR1;
	
	my $baseName = Basename($filespec,$origSuffix);
	my $dirName = Dirname($filespec);
	my $newFspec = $dirName . "/" . $baseName . $newSuffix;
	DebugMsg("baseName=$baseName dirName=$dirName newFspec=$newFspec");
	
	if(!$forceOverwrite) {
		if(!(-e $newFspec && -w _ && -f _)) {
			FatalMsg("Unable overwrite [$newFspec]: mod bits prevent, Aborting!!\007");
		}
	}
	
	open TEST_NBR2,">$newFspec" or
		FatalMsg("Unable to backup to [$newFspec]: $!, Aborting!!\007");
	close TEST_NBR2;
	
	system("cp -p $filespec $newFspec");
	if(! -e $newFspec) {
		FatalMsg("copy of $filespec to $newFspec Failed, Aborting!!\007");
	}
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   DoCmdRetOutput -- system() call with advanced ret-code analysis
##
## SYNOPSIS:
##   $ = DoCmdRetOutput($@@)
##
## EXAMPLE:
##   $retCode = DoCmdRetOutput($cmdStr,\@stdoutAr,\@stderrAr);
##
##-----------------------------------------------------------------------------
sub DoCmdRetOutput($@@)
{
	my $cmdStr = shift;
	local *stdoutAr = shift;
	local *stderrAr = shift;
	
	my $retCode = 0;	#  pre-clear return arrays
	@stdoutAr = ();
	@stderrAr = ();
	
	my $tmpDir = "/tmp/";
	if($^O =~ /win32/i) {
		if(exists $ENV{'TEMP'}) {
			$tmpDir = $ENV{'TEMP'};
			$tmpDir .= "\\";
		} else {
			$tmpDir = "";
		}
	}
	my $stdoutFname = "$tmpDir$::NAME.$$.out.tmp";
	my $stderrFname = "$tmpDir$::NAME.$$.err.tmp";
	unlink $stdoutFname if (-f $stdoutFname);
	unlink $stderrFname if (-f $stderrFname);
	
	#  add our output files to desired command
	$cmdStr .= " 1>$stdoutFname 2>$stderrFname";
	$retCode = DoCmd($cmdStr);
	
	#  load output of non-zero length
	if(-s $stdoutFname) {
		@stdoutAr = File2Array($stdoutFname);
	}
	if(-s $stderrFname) {
		@stderrAr = File2Array($stderrFname);
	}
	
	#  remove files if exist
	if (-f $stdoutFname && !defined $main::opt_debug) {
		unlink $stdoutFname or 
			Msg(-err,"DoCmdRetOutput() Failed tmp-file remove:$!\n\t- [$stdoutFname]");
	}
	if (-f $stderrFname && !defined $main::opt_debug) {
		unlink $stderrFname or
			Msg(-err,"DoCmdRetOutput() Failed tmp-file remove:$!\n\t- [$stderrFname]");
	}
	
	return $retCode;
}


##-----------------------------------------------------------------------------
## FUNCTION:
##   doCmd -- system() call with advanced ret-code analysis
##
## SYNOPSIS:
##   $ = doCmd($)
##
## EXAMPLE:
##   $retCode = doCmd($cmdStr);
##
##-----------------------------------------------------------------------------
sub DoCmd($)
{
	my $cmdStr = shift;
	my $exeName;
	my $junk;
	($exeName,$junk) = split /\s+/,$cmdStr;
	if(! -x $exeName) {
		Msg(-err,"Required command NOT executable! [$exeName]");
		return 255;
	}
	if(defined $main::opt_nodo) {
		Msg("(NODO) would execute: [$cmdStr]");
		return 0;
	}
	my $retCode = 0xffff & system($cmdStr);
	my $msgTxt = sprintf("doCmd(): system(%s) returned rc=%#04x",$cmdStr,$retCode);
	DebugMsg($msgTxt);
	foreach ($retCode) {
		/0/ and do {
			DebugMsg(" - ran with normal exit");
			last;
		};
		/0xff00/ and do {
			DebugMsg(" - command failed: $!");
			last;
		};
		if($_ > 0x80) {
			my $actualRc = $_ >> 8;
			DebugMsg(" - ran with non-zero exit status: $actualRc");
		} else {
			my $extraTxt = "";
			if($_ & 0x80) {
				$_ &= ~0x80;
				$extraTxt = "coredump from ";
			}
			DebugMsg(" - ran with ${extraTxt}signal: $_");
		}
	}
	return $retCode / 256;
}


## ---------------------------------------------------------------------
##  FUNCTION: GeneralMkdir()
##
##	   mkdir wrapped with error reporting!  Exits if fails!
## 
##  SYNOPSIS:
##   GeneralMkdir($)
##
##  EXAMPLE:
##   GeneralMkdir("/new/directory/to/make");
##
## ---------------------------------------------------------------------
sub GeneralMkdir($) 
{
	my $dirToMake = shift;
	
	my $mkdirCmd = Cmd4thisOsRev("/bin/mkdir","/usr/bin/mkdir");
	if(! -d $dirToMake) {
		my $cmdTxt = "$mkdirCmd -p $dirToMake";
		if(DoCmd($cmdTxt)) {
			FatalMsg("Failed to create dir [$dirToMake]");
		}
		if(! -d $dirToMake) {
			FatalMsg("No error but No dir, either! [$dirToMake]");
		}
		DebugMsg("Created dir [$dirToMake]");
	}
}


## ---------------------------------------------------------------------
##  FUNCTION: GetUserNames()
##
##	   return real and effective user ID's
## 
##  SYNOPSIS:
##   ($,$) = GetUserNames()
##
##  EXAMPLE:
##   ($realId,$effId) = GetUserNames();
##
## ---------------------------------------------------------------------
sub GetUserNames() 
{
	my $realIdNbr = $<;
	
	my $realId = "?{win32}?";
	my $effId = "?{win32}?";
	my $effIdNbr = $>;
	
	if($^O !~ /win32/i) {
		$realId = (getpwuid($realIdNbr))[0];
		$effId = (getpwuid($effIdNbr))[0];
	}
	
	if(exists $ENV{'USERNAME'}) {
		$realId = $ENV{'USERNAME'};
		$effId = $realId;
		DebugMsg("tkpingLib::GetUserNames() ENV{USERNAME}: realId=[$realId] effId=[$effId]");
	}
	
	#
	#  Apparently 5.003 (and earlier?) for hpux... had problems
	#   identifying real-user-id  "$<"...
	#   So... we pickup $LOGNAME from the process environment instead!
	#		-stephen
	#
	if(exists $ENV{'LOGNAME'}) {
		$realId = $ENV{'LOGNAME'};
		DebugMsg("tkpingLib::GetUserNames() ENV{LOGNAME}: realId=[$realId]");
	}
	DebugMsg("tkpingLib::GetUserNames() realId=[$realId], effId=[$effId]");
	return ($realId, $effId);
}


## ---------------------------------------------------------------------
##  FUNCTION: Cmd4thisOsRev()
##
##	   id and return proper form of command for this HP-UX rev
##       terminate if NO correct one found!
## 
##  SYNOPSIS:
##   $ = Cmd4thisOsRev($$);
##
##  EXAMPLE:
##   my $rmCmd = Cmd4thisOsRev("/bin/rm","/usr/bin/rm");
##
## ---------------------------------------------------------------------
sub Cmd4thisOsRev($$) 
{
	my $cmdLocnA = shift;
	my $cmdLocnB = shift;
	
	my $properCmd = "";
	if(-x $cmdLocnA) {
		$properCmd = $cmdLocnA;
	} elsif(-x $cmdLocnB) {
		$properCmd = $cmdLocnB;
	} else {
		FatalMsg("tkpingLib::Cmd4thisOsRev() Failed to locate usable cmd [$cmdLocnA] or [$cmdLocnB], Aborted!");
	}
	return $properCmd;
}


## ---------------------------------------------------------------------
##  FUNCTION: EnsureDirExists()
##
##	   check for dir.  Fail if doesn't exist
## 
##  SYNOPSIS:
##   EnsureDirExists($);
##
##  EXAMPLE:
##   EnsureDirExists($BINDIR,"BINDIR");
##
## ---------------------------------------------------------------------
sub EnsureDirExists($$) 
{
	my $desiredDir = shift;
	my $varName = shift;

	DebugMsg("EnsureDirExists($varName=[$desiredDir])");
	FatalMsg("Directory NOT found [$desiredDir].\007") 
		unless -d $desiredDir;
}


## ---------------------------------------------------------------------
##  FUNCTION: EnsureVariableExists()
##
##	   check for Environment Variables being set.  Fail if NOT or
##       return it's value if was.
## 
##  SYNOPSIS:
##   $ = EnsureVariableExists($);
##
##  EXAMPLE:
##   $glbMyEnvVar = EnsureVariableExists('MYENVVAR');
##
## ---------------------------------------------------------------------
sub EnsureVariableExists($)
{
	my $envVarNm = shift;
	
	if(!exists $main::ENV{$envVarNm}) {
		FatalMsg("Required environment variable NOT set [$envVarNm], Aborting!\007");
	}
	my $value = $main::ENV{$envVarNm};
	DebugMsg("EnsureVariableExists() found $envVarNm=[$value]");
	return $value;
}

## ----------------------------------------------------------------------------
## FUNCTION: DoCmdRetSingleLine - system() call with advanced ret-code 
##           analysis and single line returned from STDOUT.
##
## SYNOPSIS: $ = DoCmdRetSingleLine([-force,]$)
##
## EXAMPLE: ( $retCode, $oneLineRslt ) = DoCmdRetSingleLine($cmdStr);
##
## Stephen Moraco <stephen@cos.agilent.com>
## (written in 1998 while employed by Hewlett-Packard, Co.)
## ----------------------------------------------------------------------------
sub DoCmdRetSingleLine(@)
{
	my $rsltStr = "";

	local @txtAr = ();
	local @errAr = ();

	# note: pass all args on, including optional -force 
	# note: Passing @_ doesn't work on PC, use a string

	my $cmd = join( " ", @_ );
	my $retCode = DoCmdRetOutput( $cmd, \@txtAr, \@errAr );
	if($retCode == 0) {
		my $txtCt = @txtAr;
		if($txtCt > 1) {
			DebugMsg("DoCmdRetSingleLine() more than one line ($txtCt) of output!");
			if($txtCt <= 5) {
				my $idx=0;
				foreach (@txtAr) {
					DebugMsg(" - RsltLn$idx: $_");
				}
			}
		} elsif(@txtAr == 1) {
			$rsltStr = $txtAr[0];
		}
	}
	DebugMsg("DoCmdRetSingleLine() rsltStr=[$rsltStr]");
	return( $retCode, $rsltStr );
}

## ----------------------------------------------------------------------------
## FUNCTION:
##   Array2Fdesc -- write array to named file descriptor (which must be open)
##
##  NOTE: appends newline to each element as it is written
##
## SYNOPSIS:
##   Array2Fdesc(FSPEC,\@arrayAr); # notice the array is passed by reference!
##
## ----------------------------------------------------------------------------
sub Array2Fdesc($@) {
    my $fdesc = shift;
    local *outAr = shift;
    local ($\, $,) = ("\n", "\n");
    print $fdesc @outAr;
}

## ----------------------------------------------------------------------------
## FUNCTION:
##   ArrayRef2File -- write array to named file, overwriting file if it exists
##                   (use BackupFile() to copy before overwrite)
##
##  NOTE: appends newline to each element as it is written to file
##
## SYNOPSIS:
##   ArrayRef2File($fileSpec,\@arrayAr); # notice array passed by reference!
##
## ----------------------------------------------------------------------------
sub ArrayRef2File($@)
{
    my $filespec = shift;
    local *argAr = shift;
    local ($\, $,) = ("\n", "\n");
    my $lineCt = @argAr;
    DebugMsg("ArrayRef2File() writing",
             "$lineCt array",
             ($lineCt == 1) ? "element" : "elements",
             "to $filespec");

    #  ensure our data file exists and open it
    open(AR_DST_FILE, ">$filespec") ||
        SwengFatalMsg("ArrayRef2File(): unable to write to [$filespec]: $!");
    return if (UTFatalOccurred());  # return if under unit-test!

    # do it fast
    Array2Fdesc(AR_DST_FILE, \@argAr);

    #  close our data file
    close(AR_DST_FILE) ||
        SwengFatalMsg("ArrayRef2File(): unable to close [$filespec]: $!");
    return if (UTFatalOccurred());  # return if under unit-test!
}


## ----------------------------------------------------------------------------
##  FUNCTION: RequireDir()
##
##     Check for directory pointed to by given symbol name.  Emit error if
##     it doesn't exist.  Compare with the older EnsureDirExists().
##     IMPORTANT: if symbol name is not fully qualified, e.g. main::BINDIR,
##     then main:: is assumed.
##     Returns 1 if OK; 0 if error.
##
##  SYNOPSIS:
##   RequireDir($);
##
##  EXAMPLE:
##   $rc = 0 if (!RequireDir("BINDIR"));
##
##   Note that '$rc &&= RequireDir("BINDIR")' won't allow calls to RequireDir
##   after first error! 
##
## ----------------------------------------------------------------------------
sub RequireDir($)
{
    my $varName = shift;
    my $fullVarName = ($varName =~ /::/) ? $varName : "main::$varName";
    my $rc;

    if (!defined $$fullVarName) {
        Msg(-err, "RequireDir: variable [$varName] is not defined");
        Msg(-inf, "its value should be the name of an existing directory");
        DebugMsg(1, "fullVarName=[$fullVarName]");
        $rc = 0;
    } else {
        DebugMsg(1, "RequireDir($varName=[$$fullVarName])");
        $rc = (-d $$fullVarName) ? 1 : 0;
        Msg(-err,
            "$fullVarName [$$fullVarName] is not a directory") unless $rc;
    }
    return ($rc);
}


## ---------------------------------------------------------------------
##  FUNCTION: Assert()
##
##     First arg is a string representing an expr to eval.  If it fails,
##     the rest of the args are first passed to Msg(-inf) (one call for
##     each arg), then you get a FatalMsg() saying that the assertion
##     failed.
##
##  SYNOPSIS:
##   Assert($;@)
##
##  EXAMPLE:
##   # This asserts that $aString must have the given value.  If it
##   # doesn't, the actual value is first printed, then we get a fatal
##   # message.
##   # IMPORTANT: note that we have to use fully qualified symbol names!
##   Assert("(\main::$aString eq \"a value\")", "\$aString=[$aString]");
## ---------------------------------------------------------------------
sub Assert($;@)
{
    my $expr = shift;
    if (!eval $expr) {
        for (@_) {
            Msg(-inf, $_);
        }
        FatalMsg("Assertion failed: $expr");
    }
}



## ---------------------------------------------------------------------
##  FUNCTION: RequireParm()
##
##     extension for NGetOpt() -- forces a parm to be required
##
##  SYNOPSIS:
##   RequireParm($$$)
##
##   Given the name of the option, the global variable where the option
##   value is stored, and the documentation string to be used in an error
##   message if the parameter isn't set, will check that a parameter was
##   provided.  The name of option "someParm" will be converted to the
##   variable name $main::opt_someParm.
##
##   This works around an apparent bug in NGetOpt -- we don't trust
##   the "arg=s" syntax.
##
##   Returns 1 if OK; 0 if error.
##
##  EXAMPLE:
##
##   require "newgetopt.pl"; # defines NGetOpt()
##   $glbVariable = $NOTSET_STR; # first set to known bogus value
##   $rc = &NGetOpt("help","verbose","silent","nodo", # all standard
##                  "tag:s",\$glbTag); # our sample parm with a value
##
##   # We could also set a flag based on the return code and abort later.
##   FatalMsg("Aborting") if (!RequireParm("tag", $glbTag, "view tag"));
## ---------------------------------------------------------------------
sub RequireParm($$$)
{
    my ($optNm, $optValue, $optText) = @_;
    
    my $fullOptName = "main::opt_${optNm}";
    my $rc = 1;     # hope for the best
    
    #  detect error condition (non-renovated scripts!)
    if(defined $main::NOTSET_STR && $main::NOTSET_STR ne $NOTSET_STR) {
        Msg(-err,"Mismatched use of NOTSET_STR (now defined in tkpingLib.pm!");
        $rc = 0; # we failed
        return $rc;
    }

    #  If option is defined but value is not set, inform user that the
    #  value is required.
    #
    if (defined $$fullOptName || $optValue ne $NOTSET_STR) {
        if ($optValue eq $NOTSET_STR || $optValue eq "") {
            Msg(-err, "Option -$optNm requires $optText parameter");
            $rc = 0; # we failed
        } else {
            # User provided value, so define option so we can use it to
            # detect if value is set.
            $$fullOptName = 1;
        }
    }
    return $rc;
}


##-----------------------------------------------------------------------------
##  SPECIAL end-of-file terminator -- DO NOT REMOVE
##-----------------------------------------------------------------------------
1;	# reply OK to 'require or use'