File: Install.pm

package info (click to toggle)
libsysadm-install-perl 0.39-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 336 kB
  • sloc: perl: 734; makefile: 11
file content (1812 lines) | stat: -rw-r--r-- 42,246 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
###############################################
package Sysadm::Install;
###############################################

use 5.006;
use strict;
use warnings;

our $VERSION = '0.39';

use File::Copy;
use File::Path;
use Log::Log4perl qw(:easy);
use Log::Log4perl::Util;
use File::Basename;
use File::Spec::Functions qw(rel2abs abs2rel);
use Cwd;
use File::Temp qw(tempfile);

our $DRY_RUN;
our $CONFIRM;
our $DRY_RUN_MSG;
our $DATA_SNIPPED_LEN = 60;

dry_run(0);
confirm(0);

###############################################
sub dry_run {
###############################################
    my($on) = @_;

    if($on) {
        $DRY_RUN     = 1;
        $DRY_RUN_MSG = "(skipped - dry run)";
    } else {
        $DRY_RUN     = 0;
        $DRY_RUN_MSG = "";
    }
}

###############################################
sub confirm {
###############################################
    my($on) = @_;

    $CONFIRM = $on;
}

###########################################
sub _confirm {
###########################################
    my($msg) = @_;

    if($DRY_RUN) {
        INFO "$msg $DRY_RUN_MSG";
        return 0 if $DRY_RUN;
    }

    if($CONFIRM) {
        my $answer = ask("$msg ([y]/n)", "y");
        if($answer =~ /^\s*y\s*$/) {
            INFO $msg;
            return 1;
        }

        INFO "$msg (*CANCELLED* as requested)";
        return 0;
    }

    return 1;
}

our @EXPORTABLE = qw(
cp rmf mkd cd make 
cdback download untar 
pie slurp blurt mv tap 
plough qquote quote perm_cp owner_cp
perm_get perm_set
sysrun untar_in pick ask
hammer say
sudo_me bin_find
fs_read_open fs_write_open pipe_copy
snip password_read nice_time
def_or blurt_atomic
is_utf8_data utf8_available
printable
);

our %EXPORTABLE = map { $_ => 1 } @EXPORTABLE;

our @DIR_STACK;

##################################################
sub import {
##################################################
    my($class) = shift;

    no strict qw(refs);

    my $caller_pkg = caller();

    my(%tags) = map { $_ => 1 } @_;

        # Export all
    if(exists $tags{':all'}) {
        %tags = map { $_ => 1 } @EXPORTABLE;
    }

    for my $func (keys %tags) {
        LOGDIE __PACKAGE__ . 
            "doesn't export \"$func\"" unless exists $EXPORTABLE{$func};
        *{"$caller_pkg\::$func"} = *{$func};
    }
}

=pod

=head1 NAME

Sysadm::Install - Typical installation tasks for system administrators

=head1 SYNOPSIS

  use Sysadm::Install qw(:all);

  my $INST_DIR = '/home/me/install/';

  cd($INST_DIR);
  cp("/deliver/someproj.tgz", ".");
  untar("someproj.tgz");
  cd("someproj");

     # Write out ...
  blurt("Builder: Mike\nDate: Today\n", "build.dat");

     # Slurp back in ...
  my $data = slurp("build.dat");

     # or edit in place ...
  pie(sub { s/Today/scalar localtime()/ge; $_; }, "build.dat");

  make("test install");

     # run a cmd and tap into stdout and stderr
  my($stdout, $stderr, $exit_code) = tap("ls", "-R");

=head1 DESCRIPTION

Have you ever wished for your installation shell scripts to run
reproducably, without much programming fuzz, and even with optional
logging enabled? Then give up shell programming, use Perl.

C<Sysadm::Install> executes shell-like commands performing typical
installation tasks: Copying files, extracting tarballs, calling C<make>.
It has a C<fail once and die> policy, meticulously checking the result
of every operation and calling C<die()> immeditatly if anything fails.

C<Sysadm::Install> also supports a I<dry_run> mode, in which it 
logs everything, but suppresses any write actions. Dry run mode
is enabled by calling C<Sysadm::Install::dry_run(1)>. To switch
back to normal, call C<Sysadm::Install::dry_run(0)>.

As of version 0.17, C<Sysadm::Install> supports a I<confirm> mode,
in which it interactively asks the user before running any of its
functions (just like C<rm -i>). I<confirm> mode is enabled by calling 
C<Sysadm::Install::confirm(1)>. To switch
back to normal, call C<Sysadm::Install::confirm(0)>.

C<Sysadm::Install> is fully Log4perl-enabled. To start logging, just
initialize C<Log::Log4perl>. C<Sysadm::Install> acts as a wrapper class,
meaning that file names and line numbers are reported from the calling
program's point of view.

=head2 FUNCTIONS

=over 4

=item C<cp($source, $target)>

Copy a file from C<$source> to C<$target>. C<target> can be a directory.
Note that C<cp> doesn't copy file permissions. If you want the target
file to reflect the source file's user rights, use C<perm_cp()>
shown below.

=cut

###############################################
sub cp {
###############################################

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    _confirm("cp $_[0] $_[1]") or return 1;

    INFO "cp $_[0] $_[1]";

    File::Copy::copy @_ or 
        LOGCROAK("Cannot copy $_[0] to $_[1] ($!)");
}

=pod

=item C<mv($source, $target)>

Move a file from C<$source> to C<$target>. C<target> can be a directory.

=cut

###############################################
sub mv {
###############################################

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    _confirm("mv $_[0] $_[1]") or return 1;

    INFO "mv $_[0] $_[1]";

    File::Copy::move @_ or 
        LOGCROAK("Cannot move $_[0] to $_[1] ($!)");
}

=pod

=item C<download($url)>

Download a file specified by C<$url> and store it under the
name returned by C<basename($url)>.

=cut

###############################################
sub download {
###############################################
    my($url) = @_;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    INFO "download $url";

    _confirm("Downloading $url => ", basename($url)) or return 1;

    require LWP::UserAgent;
    require HTTP::Request;
    require HTTP::Status;

    my $ua = LWP::UserAgent->new();
    my $request = HTTP::Request->new(GET => $url);
    my $response = $ua->request($request, basename($_[0]));
    my $rc = $response->code();
    
    if($rc != HTTP::Status::RC_OK()) {
        LOGCROAK("Cannot download $_[0] (", 
                  $response->message(),
                 ")");
    }

    return 1;
}

=pod

=item C<untar($tarball)>

Untar the tarball in C<$tarball>, which typically adheres to the
C<someproject-X.XX.tgz> convention. 
But regardless of whether the 
archive actually contains a top directory C<someproject-X.XX>,
this function will behave if it had one. If it doesn't have one,
a new directory is created before the unpacking takes place. Unpacks
the tarball into the current directory, no matter where the tarfile
is located. 
Please note that if you're
using a compressed tarball (.tar.gz or .tgz), you'll need
IO::Zlib installed. 

=cut

###############################################
sub untar {
###############################################

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    LOGCROAK("untar called without defined tarfile") unless 
         @_ == 1 and defined $_[0];

    _confirm "untar $_[0]" or return 1;

    my($nice, $topdir, $namedir) = archive_sniff($_[0]);

    check_zlib($_[0]);
    require Archive::Tar;
    my $arch = Archive::Tar->new($_[0]);

    if($nice and $topdir eq $namedir) {
        DEBUG "Nice archive, extracting to subdir $topdir";
        rmf($namedir);
        $arch->extract();
    } elsif($nice) {
        DEBUG "Not-so-nice archive topdir=$topdir namedir=$namedir";
        rmf($namedir);
        rmf($topdir);
            # extract as topdir
        $arch->extract();
        rename $topdir, $namedir or 
            LOGCROAK("Can't rename $topdir, $namedir");
    } else {
        LOGCROAK("no topdir") unless defined $topdir;
        DEBUG "Not-so-nice archive (no topdir), extracting to subdir $topdir";
        $topdir = basename $topdir;
        rmf($topdir);
        mkd($topdir);
        cd($topdir);
        $arch->extract();
        cdback();
    }

    return $topdir;
}

=pod

=item C<untar_in($tar_file, $dir)>

Untar the tarball in C<$tgz_file> in directory C<$dir>. Create
C<$dir> if it doesn't exist yet.

=cut

###############################################
sub untar_in {
###############################################
    my($tar_file, $dir) = @_;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    LOGCROAK("not enough arguments") if
      ! defined $tar_file or ! defined $dir;

    _confirm "Untarring $tar_file in $dir" or return 1;

    mkd($dir) unless -d $dir;

    my $tar_file_abs = rel2abs($tar_file);

    cd($dir);

    check_zlib($tar_file_abs);
    require Archive::Tar;
    my $arch = Archive::Tar->new("$tar_file_abs");
    $arch->extract() or 
        LOGCROAK("Extract failed: ($!)");
    cdback();
}

=pod

=item C<pick($prompt, $options, $default)>

Ask the user to pick an item from a displayed list. C<$prompt>
is the text displayed, C<$options> is a referenc to an array of
choices, and C<$default> is the number (starting from 1, not 0)
of the default item. For example,

    pick("Pick a fruit", ["apple", "pear", "pineapple"], 3);

will display the following:

    [1] apple
    [2] pear
    [3] pineapple
    Pick a fruit [3]>

If the user just hits I<Enter>, "pineapple" (the default value) will
be returned. Note that 3 marks the 3rd element of the list, and is
I<not> an index value into the array.

If the user enters C<1>, C<2> or C<3>, the corresponding text string
(C<"apple">, C<"pear">, C<"pineapple"> will be returned by
C<pick()>.

=cut

##################################################
sub pick {
##################################################
    my ($prompt, $options, $default) = @_;    

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    my $default_int;
    my %files;

    if(@_ != 3 or ref($options) ne "ARRAY") {
        LOGCROAK("pick called with wrong #/type of args");
    }
    
    {
        my $count = 0;

        foreach (@$options) {
            print STDERR "[", ++$count, "] $_\n";
            $default_int = $count if $count eq $default;
            $files{$count} = $_;
        }
    
        print STDERR "$prompt [$default_int]> "
            or die "Couldn't write STDERR: ($!)";
        my $input = <STDIN>;
        chomp($input) if defined $input;

        $input = $default_int if !defined $input or !length($input);

        redo if $input !~ /^\d+$/ or 
                $input == 0 or 
                $input > scalar @$options;
        return "$files{$input}";
    }
}

=pod

=item C<ask($prompt, $default)>

Ask the user to either hit I<Enter> and select the displayed default
or to type in another string.

=cut

##################################################
sub ask {
##################################################
    my ($prompt, $default) = @_;    

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    if(@_ != 2) {
        LOGCROAK("ask() called with wrong # of args");
    }

    print STDERR "$prompt [$default]> "
        or die "Couldn't write STDERR: ($!)";

    my $value = <STDIN>;
    chomp $value;

    $value = $default if $value eq "";

    return $value;
}

=pod

=item C<mkd($dir)>

Create a directory of arbitrary depth, just like C<File::Path::mkpath>.

=cut

###############################################
sub mkd {
###############################################

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    _confirm "mkd @_" or return 1;

    INFO "mkpath @_";

    mkpath @_ or 
        LOGCROAK("Cannot mkdir @_ ($!)");
}

=pod

=item C<rmf($dir)>

Delete a directory and all of its descendents, just like C<rm -rf>
in the shell.

=cut

###############################################
sub rmf {
###############################################

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    _confirm "rmf $_[0]" or return 1;

    if(!-e $_[0]) {
        DEBUG "$_[0] doesn't exist - ignored";
        return;
    }

    INFO "rmtree @_";

    rmtree $_[0] or 
        LOGCROAK("Cannot rmtree $_[0] ($!)");
}

=pod

=item C<cd($dir)>

chdir to the given directory. If you don't want to have cd() modify
the internal directory stack (used for subsequent cdback() calls), 
set the stack_update parameter to a false value:

    cd($dir, {stack_update => 0});

=cut

###############################################
sub cd {
###############################################

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    INFO "cd $_[0]";

    my $opts = { stack_update => 1 };
    $opts = $_[1] if ref $_[1] eq "HASH";

    if ($opts->{stack_update}) {
        my $cwd = getcwd();
        if(! defined $cwd) {
            LOGCROAK("Cannot getcwd ($!)");        ;
        }
        push @DIR_STACK, $cwd;
    }

    chdir($_[0]) or 
        LOGCROAK("Cannot cd $_[0] ($!)");
}

=pod

=item C<cdback()>

chdir back to the last directory before a previous C<cd>. If the
option C<reset> is set, it goes all the way back to the beginning of the
directory stack, i.e. no matter how many cd() calls were made in between,
it'll go back to the original directory:

      # go all the way back
    cdback( { reset => 1 } );

=cut

###############################################
sub cdback {
###############################################
    my( $opts ) = @_;

    $opts = {} if !defined $opts;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    LOGCROAK("cd stack empty") unless @DIR_STACK;

    if( $opts->{ reset } ) {
        @DIR_STACK = ( $DIR_STACK[0] );
    }

    my $old_dir = pop @DIR_STACK;

    LOGCROAK("Directory stack empty")
        if ! defined $old_dir;

    INFO "cdback to $old_dir";
    cd($old_dir, {stack_update => 0});
}

=pod

=item C<make()>

Call C<make> in the shell.

=cut

###############################################
sub make {
###############################################

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    _confirm "make @_" or return 1;

    INFO "make @_";

    system("make @_") and 
        LOGCROAK("Cannot make @_ ($!)");
}

=pod

=cut

###############################################
sub check_zlib {
###############################################
    my($tar_file) = @_;

    if($tar_file =~ /\.tar\.gz\b|\.tgz\b/ and
       !Log::Log4perl::Util::module_available("IO::Zlib")) {

        LOGCROAK("$tar_file: Compressed tarballs can ",
               "only be processed with IO::Zlib installed.");
    }
}
     
#######################################
sub archive_sniff {
#######################################
    my($name) = @_;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    DEBUG "Sniffing archive '$name'";

    my ($dir) = ($name =~ /(.*?)\.(tar\.gz|tgz|tar)$/);
 
    return 0 unless defined $dir;

    $dir = basename($dir);
    DEBUG "dir=$dir";

    my $topdir;

    check_zlib($name);

    require Archive::Tar;
    my $tar = Archive::Tar->new($name);

    my @names = $tar->list_files(["name"]);
    
    LOGCROAK("Archive $name is empty") unless @names;

    (my $archdir = $names[0]) =~ s#/.*##;

    DEBUG "archdir=$archdir";

    for my $name (@names) {
        next if $name eq "./";
        $name =~ s#^\./##;
        ($topdir = $name) =~ s#/.*##;
        if($topdir ne $archdir) {
            return (0, $dir, $dir);
        }
    }

    DEBUG "Return $topdir $dir";

    return (1, $topdir, $dir);
}

=pod

=item C<pie($coderef, $filename, ...)>

Simulate "perl -pie 'do something' file". Edits files in-place. Expects
a reference to a subroutine as its first argument. It will read out the
file C<$filename> line by line and calls the subroutine setting
a localized C<$_> to the current line. The return value of the subroutine
will replace the previous value of the line.

Example:

    # Replace all 'foo's by 'bar' in test.dat
        pie(sub { s/foo/bar/g; $_; }, "test.dat");

Works with one or more file names.

If the files are known to contain UTF-8 encoded data, and you want it
to be read/written as a Unicode strings, use the C<utf8> option:

    pie(sub { s/foo/bar/g; $_; }, "test.dat", { utf8 => 1 });

=cut

###############################################
sub pie {
###############################################
    my($coderef, @files) = @_;

    my $options = {};

    if(defined $files[-1] and
       ref $files[-1] eq "HASH") {
       $options = pop @files;
    }

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    for my $file (@files) {

        _confirm "editing $file in-place" or next;

        my $out = "";

        open FILE, "<$file" or 
            LOGCROAK("Cannot open $file ($!)");

        if( $options->{utf8} ) {
            binmode FILE, ":utf8";
        }

        while(<FILE>) {
            $out .= $coderef->($_);
        }
        close FILE;

        blurt($out, $file, $options);
    }
}

=pod

=item C<plough($coderef, $filename, ...)>

Simulate "perl -ne 'do something' file". Iterates over all lines
of all input files and calls the subroutine provided as the first argument. 

Example:

    # Print all lines containing 'foobar'
        plough(sub { print if /foobar/ }, "test.dat");

Works with one or more file names.

If the files are known to contain UTF-8 encoded data, and you want it
to be read into Unicode strings, use the C<utf8> option:

    plough(sub { print if /foobar/ }, "test.dat", { utf8 => 1 });

=cut

###############################################
sub plough {
###############################################
    my($coderef, @files) = @_;

    my $options = {};

    if(defined $files[-1] and
        ref $files[-1] eq "HASH") {
        $options = pop @files;
    }

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    for my $file (@files) {

        _confirm "Ploughing through $file" or next;

        my $out = "";

        open FILE, "<$file" or 
            LOGCROAK("Cannot open $file ($!)");

        if( $options->{utf8} ) {
            binmode FILE, ":utf8";
        }

        while(<FILE>) {
            $coderef->($_);
        }
        close FILE;
    }
}

=pod

=item C<my $data = slurp($file, $options)>

Slurps in the file and returns a scalar with the file's content. If
called without argument, data is slurped from STDIN or from any files
provided on the command line (like E<lt>E<gt> operates).

If the file is known to contain UTF-8 encoded data and you want to
read it in as a Unicode string, use the C<utf8> option:

    my $unicode_string = slurp( $file, {utf8 => 1} );

=cut

###############################################
sub slurp {
###############################################
    my($file, $options) = @_;

    $options = {} unless defined $options;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    my $from_file = defined($file);

    local $/ = undef;

    my $data;

    if($from_file) {
        INFO "Slurping data from $file";
        open FILE, "<$file" or 
            LOGCROAK("Cannot open $file ($!)");
        if( exists $options->{utf8} ) {
            binmode FILE, ":utf8";
        }
        $data = <FILE>;
        close FILE;
        DEBUG "Read ", snip($data, $DATA_SNIPPED_LEN), " from $file";
    } else {
        INFO "Slurping data from <>";
        $data = <>;
        DEBUG "Read ", snip($data, $DATA_SNIPPED_LEN), " from <>";
    }

    return $data;
}

=pod

=item C<blurt($data, $file, $append)>

Opens a new file, prints the data in C<$data> to it and closes the file.
If C<$append> is set to a true value, data will be appended to the
file. Default is false, existing files will be overwritten.

If the string is a Unicode string, use the C<utf8> option:

    blurt( $unicode_string, $file, {utf8 => 1} );

=cut

###############################################
sub blurt {
###############################################
    my($data, $file, $options) = @_;

      # legacy signature
    if(defined $options and ref $options eq "") {
        $options = { append => 1 };
    }

    $options = {} unless defined $options;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    $options->{append} = 0 unless defined $options->{append};

    _confirm(($options->{append} ? "Appending" : "Writing") . " " .
         length($data) . " bytes to $file") or return 1;

    open FILE, ">" . ($options->{append} ? ">" : "") . $file 
        or 
        LOGCROAK("Cannot open $file for writing ($!)");

    if( $options->{utf8} ) {
        binmode FILE, ":utf8";
    }

    print FILE $data
        or 
        LOGCROAK("Cannot write to $file ($!)");        
    close FILE
        or 
        LOGCROAK("Cannot close $file ($!)");        

    DEBUG "Wrote ", snip($data, $DATA_SNIPPED_LEN), " to $file";
}

=pod

=item C<blurt_atomic($data, $file, $options)>

Write the data in $data to a file $file, guaranteeing that the operation
will either complete fully or not at all. This is accomplished by first
writing to a temporary file which is then rename()ed to the target file.

Unlike in C<blurt>, there is no C<$append> mode in C<blurt_atomic>.

If the string is a Unicode string, use the C<utf8> option:

    blurt_atomic( $unicode_string, $file, {utf8 => 1} );

=cut

###############################################
sub blurt_atomic {
###############################################
    my($data, $file, $options) = @_;

    _confirm("Writing atomically " .
         length($data) . " bytes to $file") or return 1;

    $options = {} unless defined $options;

    my($fh, $tmpname) = tempfile(DIR => dirname($file));

    blurt($data, $tmpname, $options);

    close $fh;

    rename $tmpname, $file or
        LOGDIE "Can't rename $tmpname to $file";

    DEBUG "Wrote ", snip($data, $DATA_SNIPPED_LEN), " atomically to $file";
}

=pod

=item C<($stdout, $stderr, $exit_code) = tap($cmd, @args)>

Run a command $cmd in the shell, and pass it @args as args.
Capture STDOUT and STDERR, and return them as strings. If
C<$exit_code> is 0, the command succeeded. If it is different,
the command failed and $exit_code holds its exit code.

Please note that C<tap()> is limited to single shell
commands, it won't work with output redirectors (C<ls E<gt>/tmp/foo>
2E<gt>&1).

In default mode, C<tap()> will concatenate the command and args
given and create a shell command line by redirecting STDERR to a temporary
file. C<tap("ls", "/tmp")>, for example, will result in

    'ls' '/tmp' 2>/tmp/sometempfile |

Note that all commands are protected by single quotes to make sure
arguments containing spaces are processed as singles, and no globbing
happens on wildcards. Arguments containing single quotes or backslashes
are escaped properly.

If quoting is undesirable, C<tap()> accepts an option hash as
its first parameter, 

    tap({no_quotes => 1}, "ls", "/tmp/*");

which will suppress any quoting:

    ls /tmp/* 2>/tmp/sometempfile |

Or, if you prefer double quotes, use

    tap({double_quotes => 1}, "ls", "/tmp/$VAR");

wrapping all args so that shell variables are interpolated properly:

    "ls" "/tmp/$VAR" 2>/tmp/sometempfile |

Another option is "utf8" which runs the command in a terminal set to 
UTF8.

Error handling: By default, tap() won't raise an error if the command's
return code is nonzero, indicating an error reported by the shell. If 
bailing out on errors is requested to avoid return code checking by
the script, use the raise_error option:

    tap({raise_error => 1}, "ls", "doesn't exist");

=cut

###############################################
sub tap {
###############################################
    my(@args) = @_;

    my $options = {};

    if(defined $args[-1] and
       ref $args[-1] eq "HASH") {
       $options = pop @args;
    }

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    _confirm "tapping @args" or return 1;

    my $opts = {};

    $opts = shift @args if ref $args[0] eq "HASH";

    my $tmpfh   = File::Temp->new(UNLINK => 1, SUFFIX => '.dat');
    my $tmpfile = $tmpfh->filename();

    DEBUG "tempfile $tmpfile created";

    my $cmd;

    if($opts->{no_quotes}) {
        $cmd = join ' ', @args;
    } elsif($opts->{double_quotes}) {
        $cmd = join ' ', map { qquote($_, ":shell") } @args;
    } else {
            # Default mode: Single quotes
        $cmd = join ' ', map { quote($_, ":shell") } @args;
    }
       
    $cmd = "$cmd 2>$tmpfile |";
    INFO "tapping $cmd";

    open PIPE, $cmd or 
        LOGCROAK("open $cmd | failed ($!)");
        
    if( $options->{utf8} ) {
        binmode PIPE, ":utf8";
    }

    my $stdout = join '', <PIPE>;
    close PIPE;

    my $exit_code = $?;

    if($exit_code != 0 and $opts->{raise_error}) {
        LOGCROAK("tap $cmd | failed ($!)");
    }

    my $stderr = slurp($tmpfile, $options);

    DEBUG "tap $cmd results: rc=$exit_code stderr=[$stderr] stdout=[$stdout]";

    return ($stdout, $stderr, $exit_code);
}

=pod

=item C<$quoted_string = qquote($string, [$metachars])>

Put a string in double quotes and escape all sensitive characters so
there's no unwanted interpolation. 
E.g., if you have something like

   print "foo!\n";

and want to put it into a double-quoted string, it will look like

    "print \"foo!\\n\""

Sometimes, not only backslashes and double quotes need to be escaped,
but also the target environment's meta chars. A string containing

    print "$<\n";

needs to have the '$' escaped like

    "print \"\$<\\n\";"

if you want to reuse it later in a shell context:

    $ perl -le "print \"\$<\\n\";"
    1212

C<qquote()> supports escaping these extra characters with its second,
optional argument, consisting of a string listing  all escapable characters:

    my $script  = 'print "$< rocks!\\n";';
    my $escaped = qquote($script, '!$'); # Escape for shell use
    system("perl -e $escaped");

    => 1212 rocks!

And there's a shortcut for shells: By specifying ':shell' as the
metacharacters string, qquote() will actually use '!$`'.

For example, if you wanted to run the perl code

    print "foobar\n";

via

    perl -e ...

on a box via ssh, you would use

    use Sysadm::Install qw(qquote);

    my $cmd = 'print "foobar!\n"';
       $cmd = "perl -e " . qquote($cmd, ':shell');
       $cmd = "ssh somehost " . qquote($cmd, ':shell');

    print "$cmd\n";
    system($cmd);

and get

    ssh somehost "perl -e \"print \\\"foobar\\\!\\\\n\\\"\""

which runs on C<somehost> without hickup and prints C<foobar!>.

Sysadm::Install comes with a script C<one-liner> (installed in bin),
which takes arbitrary perl code on STDIN and transforms it into
a one-liner:

    $ one-liner
    Type perl code, terminate by CTRL-D
    print "hello\n";
    print "world\n";
    ^D
    perl -e "print \"hello\\n\"; print \"world\\n\"; "

=cut

###############################################
sub qquote {
###############################################
    my($str, $metas) = @_;

    $str =~ s/([\\"])/\\$1/g;

    if(defined $metas) {
        $metas = '!$`' if $metas eq ":shell";
        $metas =~ s/\]/\\]/g;
        $str =~ s/([$metas])/\\$1/g;
    }

    return "\"$str\"";
}

=pod

=item C<$quoted_string = quote($string, [$metachars])>

Similar to C<qquote()>, just puts a string in single quotes and
escapes what needs to be escaped.

Note that shells typically don't support escaped single quotes within
single quotes, which means that

    $ echo 'foo\'bar'
    >

is invalid and the shell waits until it finds a closing quote. 
Instead, there is an evil trick which gives the desired result:

    $ echo 'foo'\''bar'  # foo, single quote, \, 2 x single quote, bar
    foo'bar

It uses the fact that shells interpret back-to-back strings as one.
The construct above consists of three back-to-back strings: 

    (1) 'foo'
    (2) '
    (3) 'bar'

which all get concatenated to a single 

    foo'bar

If you call C<quote()> with C<$metachars> set to ":shell", it will
perform that magic behind the scenes:

    print quote("foo'bar");
      # prints: 'foo'\''bar'

=cut

###############################################
sub quote {
###############################################
    my($str, $metas) = @_;

    if(defined $metas and $metas eq ":shell") {
        $str =~ s/([\\])/\\$1/g;
        $str =~ s/(['])/'\\''/g;
    } else {
        $str =~ s/([\\'])/\\$1/g;
    }

    if(defined $metas and $metas ne ":shell") {
        $metas =~ s/\]/\\]/g;
        $str =~ s/([$metas])/\\$1/g;
    }

    return "\'$str\'";
}

=pod

=item C<perm_cp($src, $dst, ...)>

Read the C<$src> file's user permissions and modify all
C<$dst> files to reflect the same permissions.

=cut

######################################
sub perm_cp {
######################################
    # Lifted from Ben Okopnik's
    # http://www.linuxgazette.com/issue87/misc/tips/cpmod.pl.txt

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    _confirm "perm_cp @_" or return 1;

    LOGCROAK("usage: perm_cp src dst ...") if @_ < 2;

    my $perms = perm_get($_[0]);
    perm_set($_[1], $perms);
}

=pod

=item C<owner_cp($src, $dst, ...)>

Read the C<$src> file/directory's owner uid and group gid and apply
it to $dst.

For example: copy uid/gid of the containing directory to a file
therein:

    use File::Basename;

    owner_cp( dirname($file), $file );

Usually requires root privileges, just like chown does.

=cut

######################################
sub owner_cp {
######################################
    my($src, @dst) = @_;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    _confirm "owner_cp @_" or return 1;

    LOGCROAK("usage: owner_cp src dst ...") if @_ < 2;

    my($uid, $gid) = (stat($src))[4,5];

    if(!defined $uid or !defined $gid ) {
        LOGCROAK("stat of $src failed: $!");
        return undef;
    }

    if(!chown $uid, $gid, @dst ) {
        LOGCROAK("chown of ", join(" ", @dst), " failed: $!");
        return undef;
    }

    return 1;
}

=pod

=item C<$perms = perm_get($filename)>

Read the C<$filename>'s user permissions and owner/group. 
Returns an array ref to be
used later when calling C<perm_set($filename, $perms)>.

=cut 

######################################
sub perm_get {
######################################
    my($filename) = @_;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    my @stats = (stat $filename)[2,4,5] or
        
        LOGCROAK("Cannot stat $filename ($!)");

    INFO "perm_get $filename (@stats)";

    return \@stats;
}

=pod

=item C<perm_set($filename, $perms)>

Set file permissions and owner of C<$filename>
according to C<$perms>, which was previously
acquired by calling C<perm_get($filename)>.

=cut 

######################################
sub perm_set {
######################################
    my($filename, $perms) = @_;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    _confirm "perm_set $filename (@$perms)" or return 1;

    chown($perms->[1], $perms->[2], $filename) or 
        
        LOGCROAK("Cannot chown $filename ($!)");
    chmod($perms->[0] & 07777,    $filename) or
        
        LOGCROAK("Cannot chmod $filename ($!)");
}

=pod

=item C<sysrun($cmd)>

Run a shell command via C<system()> and die() if it fails. Also 
works with a list of arguments, which are then interpreted as program
name plus arguments, just like C<system()> does it.

=cut

######################################
sub sysrun {
######################################
    my(@cmds) = @_;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    _confirm "sysrun: @cmds" or return 1;

    LOGCROAK("usage: sysrun cmd ...") if @_ < 1;

    system(@cmds) and 
        LOGCROAK("@cmds failed ($!)");
}

=pod

=item C<hammer($cmd, $arg, ...)>

Run a command in the shell and simulate a user hammering the
ENTER key to accept defaults on prompts.

=cut

######################################
sub hammer {
######################################
    my(@cmds) = @_;

    require Expect;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

        _confirm "Hammer: @cmds" or return 1;

    my $exp = Expect->new();
    $exp->raw_pty(0);

    INFO "spawning: @cmds";
    $exp->spawn(@cmds);

    $exp->send_slow(0.1, "\n") for 1..199;
    $exp->expect(undef);
}

=pod

=item C<say($text, ...)>

Alias for C<print ..., "\n">, just like Perl6 is going to provide it.

=cut

######################################
sub say {
######################################
    print @_, "\n";
}

=pod

=item C<sudo_me()>

Check if the current script is running as root. If yes, continue. If not,
restart the current script with all command line arguments is restarted
under sudo:

    sudo scriptname args ...

Make sure to call this before any C<@ARGV>-modifying functions like
C<getopts()> have kicked in.

=cut

######################################
sub sudo_me {
######################################
    my($argv) = @_;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    _confirm "sudo_me" or return 1;

    $argv = \@ARGV unless $argv;

       # If we're not running as root, 
       # re-invoke the script via sudo
    if($> != 0) {
        DEBUG "Not running as root, calling sudo $0 @$argv";
        my $sudo = bin_find("sudo");
        LOGCROAK("Can't find sudo in PATH") unless $sudo;
        exec($sudo, $0, @$argv) or 
            LOGCROAK("exec failed!");
    }
}

=pod

=item C<bin_find($program)>

Search all directories in $PATH (the ENV variable) for an executable
named $program and return the full path of the first hit. Returns
C<undef> if the program can't be found.

=cut

######################################
sub bin_find {
######################################
    my($exe) = @_;

    require Config;
    my $path_sep = ":";
    $path_sep = $Config::Config{path_sep} if defined $Config::Config{path_sep};

    for my $path (split /$path_sep/, $ENV{PATH}) {
        my $full = File::Spec->catfile($path, $exe);

        return $full if -x $full and ! -d $full;
    }

    return undef;
}

=pod

=item C<fs_read_open($dir)>

Opens a file handle to read the output of the following process:

    cd $dir; find ./ -xdev -print0 | cpio -o0 |

This can be used to capture a file system structure. 

=cut

######################################
sub fs_read_open {
######################################
    my($dir, $options) = @_;

    $options = {} unless defined $options;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    my $find = bin_find("find");
    LOGCROAK("Cannot find 'find'") unless defined $find;

    my $cpio = bin_find("cpio");
    LOGCROAK("Cannot find 'cpio'") unless defined $cpio;

    cd $dir;
 
    my $cmd = "$find . -xdev -print0 | $cpio -o0 --quiet 2>/dev/null ";

    DEBUG "Reading from $cmd";
    open my $in, "$cmd |" or 
        LOGCROAK("Cannot open $cmd");

    binmode $in, ":utf8" if $options->{utf8};

    cdback;

    return $in;
}

=pod

=item C<fs_write_open($dir)>

Opens a file handle to write to a 

    | (cd $dir; cpio -i0)

process to restore a file system structure. To be used in conjunction
with I<fs_read_open>.

=cut

######################################
sub fs_write_open {
######################################
    my($dir, $options) = @_;

    $options = {} unless defined $options;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    my $cpio = bin_find("cpio");
    LOGCROAK("Cannot find 'cpio'") unless defined $cpio;

    mkd $dir unless -d $dir;

    cd $dir;

    my $cmd = "$cpio -i0 --quiet";

    DEBUG "Writing to $cmd in dir $dir";
    open my $out, "| $cmd" or 
        LOGCROAK("Cannot open $cmd");

    binmode $out, ":utf8" if $options->{utf8};

    cdback;

    return $out;
}

=pod

=item C<pipe_copy($in, $out, [$bufsize])>

Reads from $in and writes to $out, using sysread and syswrite. The
buffer size used defaults to 4096, but can be set explicitly.

=cut

######################################
sub pipe_copy {
######################################
    my($in, $out, $bufsize) = @_;

    local $Log::Log4perl::caller_depth =
          $Log::Log4perl::caller_depth + 1;

    $bufsize ||= 4096;
    my $bytes = 0;

    INFO "Opening pipe (bufsize=$bufsize)";
    my $ret;
    while($ret = sysread($in, my $buf, $bufsize)) {
        $bytes += length $buf;
        if (!defined syswrite $out, $buf) {
            LOGCROAK("Write to pipe failed: ($!)");
        }
    }
    if (!defined $ret) {
        LOGCROAK("Read from pipe failed: ($!)");
    }
    INFO "Closed pipe (bufsize=$bufsize, transferred=$bytes)";
}

=pod

=item C<snip($data, $maxlen)>

Format the data string in C<$data> so that it's only (roughly) $maxlen
characters long and only contains printable characters.

If C<$data> is longer than C<$maxlen>, it will be
formatted like

    (22)[abcdef[snip=11]stuvw]

indicating the length of the original string, the beginning, the
end, and the number of 'snipped' characters.

If C<$data> is shorter than $maxlen, it will be returned unmodified 
(except for unprintable characters replaced, see below).

If C<$data> contains unprintable character's they are replaced by 
"." (the dot).

=cut

###########################################
sub snip {
###########################################
    my($data, $maxlen) = @_;

    if(length $data <= $maxlen) {
        return printable($data);
    }

    $maxlen = 12 if $maxlen < 12;
    my $sniplen = int(($maxlen - 8) / 2);

    my $start   = substr($data,  0, $sniplen);
    my $end     = substr($data, -$sniplen);
    my $snipped = length($data) - 2*$sniplen;

    return lenformat("$start\[snip=$snipped]$end", length $data);
}
    
###########################################
sub lenformat {
###########################################
    my($data, $orglen) = @_;

    return "(" . ($orglen || length($data)) . ")[" .
        printable($data) . "]";
}

###########################################
sub printable {
###########################################
    my($data) = @_;

    $data =~ s/[^ \w.;!?@#$%^&*()+\\|~`',><[\]{}="-]/./g;
    return $data;
}

=pod

=item C<password_read($prompt)>

Reads in a password to be typed in by the user in noecho mode.
A call to password_read("password: ") results in

    password: ***** (stars aren't actually displayed)

This function will switch the terminal back into normal mode
after the user hits the 'Return' key.

=cut

###########################################
sub password_read {
###########################################
    my($prompt) = @_;

    use Term::ReadKey;
    ReadMode 'noecho';
    $| = 1;
    print "$prompt"
        or die "Couldn't write STDOUT: ($!)";
    my $pw = ReadLine 0;
    chomp $pw;
    ReadMode 'restore';
    print "\n"
        or die "Couldn't write STDOUT: ($!)";

    return $pw;
}

=pod

=item C<nice_time($time)>

Format the time in a human-readable way, less wasteful than the 
'scalar localtime' formatting. 

    print nice_time(), "\n";
      # 2007/04/01 10:51:24

It uses the system time by default, but it can also accept epoch seconds:

    print nice_time(1170000000), "\n";
      # 2007/01/28 08:00:00

It uses localtime() under the hood, so the outcome of the above will
depend on your local time zone setting.

=cut

###########################################
sub nice_time {
###########################################
    my($time) = @_;

    $time = time() unless defined $time;

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

    return sprintf("%d/%02d/%02d %02d:%02d:%02d",
     $year+1900, $mon+1, $mday,
     $hour, $min, $sec);
}

=item C<def_or($foo, $default)>

Perl-5.9 added the //= construct, which helps assigning values to
undefined variables. Instead of writing

    if(!defined $foo) {
        $foo = $default;
    }

you can just write

    $foo //= $default;

However, this is not available on older perl versions (although there's 
source filter solutions). Often, people use

    $foo ||= $default;

instead which is wrong if $foo contains a value that evaluates as false.
So Sysadm::Install, the everything-and-the-kitchen-sink under the CPAN
modules, provides the function C<def_or()> which can be used like

    def_or($foo, $default); 

to accomplish the same as

    $foo //= $default;

How does it work, how does $foo get a different value, although it's 
apparently passed in by value? Modifying $_[0] within the subroutine
is an old Perl trick to do exactly that.

=cut

###########################################
sub def_or($$) {
###########################################
    if(! defined $_[0]) {
        $_[0] = $_[1];
    }
}

=item C<is_utf8_data($data)>

Check if the given string has the utf8 flag turned on. Works just like 
Encode.pm's is_utf8() function, except that it silently returns a 
false if Encode isn't available, for example when an ancient perl 
without proper utf8 support is used.

=cut

###############################################
sub is_utf8_data {
###############################################
    my($data) = @_;

    if( !utf8_available() ) {
        return 0;
    }

    return Encode::is_utf8( $data );
}

=item C<utf8_check($data)>

Check if we're using a perl with proper utf8 support, by verifying the
Encode.pm module is available for loading.

=cut

###############################################
sub utf8_available {
###############################################

    eval "use Encode";

    if($@) {
        return 0;
    }

    return 1;
}


=pod

=back

=head1 AUTHOR

Mike Schilli, E<lt>m@perlmeister.comE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2004-2007 by Mike Schilli

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.3 or,
at your option, any later version of Perl 5 you may have available.

=cut

1;