package run_program; # $Id$ use diagnostics; use strict; use MDK::Common; use log; 1; sub run_or_die { my ($name, @args) = @_; run($name, @args) or die "$name failed\n"; } sub rooted_or_die { my ($root, $name, @args) = @_; rooted($root, $name, @args) or die "$name failed\n"; } sub get_stdout { my ($name, @args) = @_; my @r; run($name, '>', \@r, @args) or return; wantarray() ? @r : join('', @r); } sub rooted_get_stdout { my ($root, $name, @args) = @_; my @r; rooted($root, $name, '>', \@r, @args) or return; wantarray() ? @r : join('', @r); } sub run { raw({}, @_) } sub rooted { my ($root, $name, @args) = @_; raw({ root => $root }, $name, @args); } sub raw { my ($options, $name, @args) = @_; my $root = $options->{root} || ''; my $str = ref($name) ? $name->[0] : $name; log::l("running: $str @args" . ($root ? " with root $root" : "")); return 1 if $root && $<; $root ? ($root .= '/') : ($root = ''); install_any::check_prog(ref($name) ? $name->[0] : $name) if !$root && $::isInstall; my ($stdout_raw, $stdout_mode, $stderr_raw, $stderr_mode); ($stdout_mode, $stdout_raw, @args) = @args if $args[0] =~ /^>>?$/; ($stderr_mode, $stderr_raw, @args) = @args if $args[0] =~ /^2>>?$/; $ENV{HOME} || $::isInstall or $ENV{HOME} = '/root'; my $stdout = $stdout_raw && (ref($stdout_raw) ? "$ENV{HOME}/tmp/.drakx-stdout.$$" : "$root$stdout_raw"); my $stderr = $stderr_raw && (ref($stderr_raw) ? "$ENV{HOME}/tmp/.drakx-stderr.$$" : "$root$stderr_raw"); if (my $pid = fork()) { my $ok; eval { local $SIG{ALRM} = sub { die "ALARM" }; alarm($options->{timeout} || 10 * 60); waitpid $pid, 0; $ok = $? == 0; alarm 0; }; if ($@) { log::l("ERROR: killing runaway process"); kill 9, $pid; return; } if ($stdout_raw && ref($stdout_raw)) { if (ref($stdout_raw) eq 'ARRAY') { @$stdout_raw = cat_($stdout); } else { $$stdout_raw = cat_($stdout); } unlink $stdout; } if ($stderr_raw && ref($stderr_raw)) { if (ref($stderr_raw) eq 'ARRAY') { @$stderr_raw = cat_($stderr); } else { $$stderr_raw = cat_($stderr); } unlink $stderr; } $ok; } else { if ($stderr && $stderr eq 'STDERR') { } elsif ($stderr) { $stderr_mode =~ s/2//; open STDERR, "$stderr_mode $stderr" or die "run_program can't output in $stderr (mode `$stderr_mode')"; } elsif ($::isInstall) { open STDERR, ">> /tmp/ddebug.log" or open STDOUT, ">> /dev/tty7" or die "run_program can't log, give me access to /tmp/ddebug.log"; } if ($stdout && $stdout eq 'STDOUT') { } elsif ($stdout) { open STDOUT, "$stdout_mode $stdout" or die "run_program can't output in $stdout (mode `$stdout_mode')"; } elsif ($::isInstall) { open STDOUT, ">> /tmp/ddebug.log" or open STDOUT, ">> /dev/tty7" or die "run_program can't log, give me access to /tmp/ddebug.log"; } $root and chroot $root; chdir "/"; if (ref $name) { unless (exec { $name->[0] } $name->[1], @args) { log::l("exec of $name->[0] failed: $!"); c::_exit(128); } } else { unless (exec $name, @args) { log::l("exec of $name failed: $!"); c::_exit(128); } } } } f338'>plain)
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
# vim: set et ts=4 sw=4:
package ManaTools::Shared::TimeZone;

#============================================================= -*-perl-*-

=head1 NAME

ManaTools::Shared::TimeZone - module to manage TimeZone settings

=head1 SYNOPSIS

    my $tz = ManaTools::Shared::TimeZone->new();


=head1 DESCRIPTION

This module allows to manage time zone settings.

=head1 SUPPORT

You can find documentation for this module with the perldoc command:

perldoc ManaTools::Shared::TimeZone


=head1 AUTHOR

Angelo Naselli <anaselli@linux.it>

=head1 COPYRIGHT and LICENSE

Copyright (C) 2014-2015, Angelo Naselli.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2, as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

=head1 METHODS

=cut


use diagnostics;
use strict;

use Moose;
use English;
use Sys::Syslog;

use DateTime::TimeZone;
use Net::DBus;

use ManaTools::Shared::Locales;
use ManaTools::Shared::Services;

use MDK::Common::File qw(cat_ output_p substInFile);
use MDK::Common::Func qw(find if_);


#=============================================================

=head2 new - optional parameters

=head3 timezone_prefix

    optional parameter to set the system timezone directory,
    default value is /usr/share/zoneinfo

=cut

#=============================================================

has 'timezone_prefix' => (
    is => 'rw',
    isa => 'Str',
    default => "/usr/share/zoneinfo",
);


#=============================================================

=head2 new - optional parameters

=head3 ntp_configuration_file

    optional parameter to set the ntp server configuration file,
    it meant to be for testing purpose, do not set or it will
    be considered as configuration file despite of what the ntp
    service is.

=cut

#=============================================================

has 'ntp_configuration_file' => (
    is  => 'rw',
    isa => 'Str',
);


#=============================================================

=head2 new - optional parameters

=head3 ntp_conf_dir

    optional parameter to set ntp configuration directory,
    default value is /etc/ntp

=cut

#=============================================================

has 'ntp_conf_dir' => (
    is   => 'rw',
    isa  => 'Str',
    lazy => 1,
    default => "/etc/ntp",
);

#=============================================================

=head2 new - optional parameters

=head3 ntp_program

    optional parameter to set the ntp program that runs into the
    system, available value are chronyd, ntpd and systemd-timesyncd.

    Default value is evaluate by configuration file found in the
    system, fallback choice is systemd-timesyncd.

=cut

#=============================================================
has 'ntp_program' => (
    is      => 'rw',
    isa     => 'Str',
    lazy    => 1,
    builder => '_ntp_program_init',
);

sub _ntp_program_init {
    my $self = shift;

    # looks for a running service from the configured ones,
    # if none is running chooses the first of the list
    my $list = $self->ntpServiceList();
    return "" if !$list || scalar @{$list} == 0;

    my $ntpd = "";
    my $isRunning = 0;

    foreach (@{$list}) {
        $ntpd = $_;
        $isRunning = $self->sh_services->is_service_running($ntpd);
        last if $isRunning;
    }

    if (!$isRunning) {
        # being sure systemd-timesyncd is not really running (or set to be)
        if ($self->getEmbeddedNTP()) {
            $ntpd = "systemd-timesyncd";
            Sys::Syslog::syslog(
                'info|local1',
                $self->loc->N("%s enabled but stopped - disabling it",
                    $ntpd
                )
            );
            # enabled but stopped, disabling it
            # NOTE this happens tipically on VM if not well configured
            $self->setEmbeddedNTP(0);
        }
        else {
            # coosing the first one of the list that is not running
            $ntpd = $list->[0];
        }
    }

    return $ntpd;
}

#=============================================================

=head2 attribute

=head3 ntpServiceConfig

    This RO attribute is a HashRef containing managed ntp
    service as key and related configuration file.

    Allowed actions:
        getNTPServiceConfig => retrieves config file from the
                               given ntp service
        ntpServiceConfigPairs => Key,Value pairs access

=cut

#=============================================================
has 'ntpServiceConfig' => (
    traits    => ['Hash'],
    default   => sub { {
        'chronyd'           => '/etc/chrony.conf',
        'ntpd'              => '/etc/ntp.conf',
        'systemd-timesyncd' => '/etc/systemd/timesyncd.conf'
    } },
    is        => 'ro',
    isa       => 'HashRef',
    handles   => {
        getNTPServiceConfig   => 'get',
        ntpServiceConfigPairs => 'kv',
    },
    init_arg  => undef,
);

#=============================================================

=head2 attribute

=head3 ntpServiceList

    This attribute is a ArrayRef containing the sorted list of
    configured NTP service into the system, retrieving info from
    services.

=cut

#=============================================================
has 'ntpServiceList' => (
    is      => 'rw',
    isa     => 'ArrayRef',
    lazy    => 1,
    builder => '_build_ntpServiceList',
    init_arg  => undef,
);

# retrieves the installed ntp service list
sub _build_ntpServiceList {
    my $self = shift();

    my @list = ();
    for my $pair ($self->ntpServiceConfigPairs()) {
        push @list, $pair->[0] if eval {$self->sh_services->dbus_systemd1_object->GetUnitFileState( $pair->[0] . ".service")};
    }

    return [ sort(@list) ];
}

#=============================================================

=head2 new - optional parameters

=head3 installer_or_livecd

    To inform the back-end that is working during installer or
    livecd. Useful if Time zone setting and using fix_system
    to use the real time clock (see setLocalRTC and
    writeConfiguration).

=cut

#=============================================================
has 'installer_or_livecd' => (
    is  => 'rw',
    isa => 'Bool',
    default => 0,
);

#=== globals ===

has 'sh_services' => (
        is => 'rw',
        init_arg => undef,
        lazy     => 1,
        builder => '_SharedServicesInitialize'
);

sub _SharedServicesInitialize {
    my $self = shift();

    $self->sh_services(ManaTools::Shared::Services->new(include_static_services => 1) );
}


has 'dbus_timedate1_service' => (
    is       => 'rw',
    init_arg => undef,
    lazy     => 1,
    builder  => '_dbusTimeDateInitialize'
);

sub _dbusTimeDateInitialize {
    my $self = shift();

    my $bus = Net::DBus->system;
    $self->dbus_timedate1_service($bus->get_service("org.freedesktop.timedate1"));
}


has 'dbus_timedate1_object' => (
    is       => 'rw',
    init_arg => undef,
    lazy     => 1,
    builder  => '_dbusObjectInitialize'
);

sub _dbusObjectInitialize {
    my $self = shift();

    $self->dbus_timedate1_object($self->dbus_timedate1_service->get_object("/org/freedesktop/timedate1"));
}


has 'servername_config_suffix' => (
    is  => 'ro',
    isa => 'Str',
    lazy     => 1,
    builder  => '_servername_config_suffix_init',
);

sub _servername_config_suffix_init {
    my $self = shift;

    return " iburst" if ($self->ntp_program eq "chronyd");

    return "";
}

has 'loc' => (
        is       => 'rw',
        lazy     => 1,
        init_arg => undef,
        builder  => '_localeInitialize'
);

sub _localeInitialize {
    my $self = shift;

    my $cmdline    = new yui::YCommandLine;
    my $locale_dir = undef;
    my $pos        = $cmdline->find("--locales-dir");
    if ($pos > 0)
    {
       $locale_dir = $cmdline->arg($pos+1);
    }
    $self->loc(
        ManaTools::Shared::Locales->new(
            domain_name => 'manatools',
            dir_name    => $locale_dir,
        )
    );
}

has 'ntp_servers' => (
    traits    => ['Hash'],
    is        => 'rw',
    isa       => 'HashRef',
    lazy      => 1,
    handles   => {
        get_ntp_server     => 'get',
        ntp_server_pairs   => 'kv',
    },
    init_arg  => undef,
    builder => '_buildNTPServers'
);

sub _buildNTPServers {
    my $self = shift;

    my %ntpServersHash;
    $ntpServersHash{"-"} = {
        $self->loc->N_("Global") => "pool.ntp.org",
    };
    $ntpServersHash{Global} = {
        $self->loc->N_("Africa") => "africa.pool.ntp.org",
        $self->loc->N_("Asia") => "asia.pool.ntp.org",
        $self->loc->N_("Europe") => "europe.pool.ntp.org",
        $self->loc->N_("North America") => "north-america.pool.ntp.org",
        $self->loc->N_("Oceania") => "oceania.pool.ntp.org",
        $self->loc->N_("South America") => "south-america.pool.ntp.org",
    };
    $ntpServersHash{Africa} = {
        $self->loc->N_("South Africa") => "za.pool.ntp.org",
        $self->loc->N_("Tanzania") => "tz.pool.ntp.org",
    };
    $ntpServersHash{Asia} = {
        $self->loc->N_("Bangladesh") => "bd.pool.ntp.org",
        $self->loc->N_("China") => "cn.pool.ntp.org",
        $self->loc->N_("Hong Kong") => "hk.pool.ntp.org",
        $self->loc->N_("India") => "in.pool.ntp.org",
        $self->loc->N_("Indonesia") => "id.pool.ntp.org",
        $self->loc->N_("Iran") => "ir.pool.ntp.org",
        $self->loc->N_("Israel") => "il.pool.ntp.org",
        $self->loc->N_("Japan") => "jp.pool.ntp.org",
        $self->loc->N_("Korea") => "kr.pool.ntp.org",
        $self->loc->N_("Malaysia") => "my.pool.ntp.org",
        $self->loc->N_("Philippines") => "ph.pool.ntp.org",
        $self->loc->N_("Singapore") => "sg.pool.ntp.org",
        $self->loc->N_("Taiwan") => "tw.pool.ntp.org",
        $self->loc->N_("Thailand") => "th.pool.ntp.org",
        $self->loc->N_("Turkey") => "tr.pool.ntp.org",
        $self->loc->N_("United Arab Emirates") => "ae.pool.ntp.org",
    };
    $ntpServersHash{Europe} = {
        $self->loc->N_("Austria") => "at.pool.ntp.org",
        $self->loc->N_("Belarus") => "by.pool.ntp.org",
        $self->loc->N_("Belgium") => "be.pool.ntp.org",
        $self->loc->N_("Bulgaria") => "bg.pool.ntp.org",
        $self->loc->N_("Czech Republic") => "cz.pool.ntp.org",
        $self->loc->N_("Denmark") => "dk.pool.ntp.org",
        $self->loc->N_("Estonia") => "ee.pool.ntp.org",
        $self->loc->N_("Finland") => "fi.pool.ntp.org",
        $self->loc->N_("France") => "fr.pool.ntp.org",
        $self->loc->N_("Germany") => "de.pool.ntp.org",
        $self->loc->N_("Greece") => "gr.pool.ntp.org",
        $self->loc->N_("Hungary") => "hu.pool.ntp.org",
        $self->loc->N_("Ireland") => "ie.pool.ntp.org",
        $self->loc->N_("Italy") => "it.pool.ntp.org",
        $self->loc->N_("Lithuania") => "lt.pool.ntp.org",
        $self->loc->N_("Luxembourg") => "lu.pool.ntp.org",
        $self->loc->N_("Netherlands") => "nl.pool.ntp.org",
        $self->loc->N_("Norway") => "no.pool.ntp.org",
        $self->loc->N_("Poland") => "pl.pool.ntp.org",
        $self->loc->N_("Portugal") => "pt.pool.ntp.org",
        $self->loc->N_("Romania") => "ro.pool.ntp.org",
        $self->loc->N_("Russian Federation") => "ru.pool.ntp.org",
        $self->loc->N_("Slovakia") => "sk.pool.ntp.org",
        $self->loc->N_("Slovenia") => "si.pool.ntp.org",
        $self->loc->N_("Spain") => "es.pool.ntp.org",
        $self->loc->N_("Sweden") => "se.pool.ntp.org",
        $self->loc->N_("Switzerland") => "ch.pool.ntp.org",
        $self->loc->N_("Ukraine") => "ua.pool.ntp.org",
        $self->loc->N_("United Kingdom") => "uk.pool.ntp.org",
        $self->loc->N_("Yugoslavia") => "yu.pool.ntp.org",
    };
    $ntpServersHash{"North America"} = {
        $self->loc->N_("Canada") => "ca.pool.ntp.org",
        $self->loc->N_("Guatemala") => "gt.pool.ntp.org",
        $self->loc->N_("Mexico") => "mx.pool.ntp.org",
        $self->loc->N_("United States") => "us.pool.ntp.org",
    };
    $ntpServersHash{Oceania} = {
        $self->loc->N_("Australia") => "au.pool.ntp.org",
        $self->loc->N_("New Zealand") => "nz.pool.ntp.org",
    };
    $ntpServersHash{"South America"} = {
        $self->loc->N_("Argentina") => "ar.pool.ntp.org",
        $self->loc->N_("Brazil") => "br.pool.ntp.org",
        $self->loc->N_("Chile") => "cl.pool.ntp.org",
    };

    return \%ntpServersHash;
}


#=============================================================

=head2 refreshNTPServiceList

=head3 DESCRIPTION

    Refresh the ntpServiceList attribute value, usefull
    if any NTP service has been istalled after having
    instantiated this object

=cut

#=============================================================
sub refreshNTPServiceList {
    my $self = shift;

    my $list = $self->_build_ntpServiceList();

    $self->ntpServiceList($list);
}

#=============================================================

=head2 get_timezone_prefix

=head3 OUTPUT

timezone_prefix: directory in which time zone files are

=head3 DESCRIPTION

Return the timezone directory (defualt: /usr/share/zoneinfo)

=cut

#=============================================================
sub get_timezone_prefix {
    my $self = shift;

    return $self->timezone_prefix;
}

#=============================================================

=head2 getTimeZones

=head3 INPUT

    $from_system: if present and its value is not 0 checks into timezone_prefix
                directory and gets the list from there

=head3 OUTPUT

    @l: ARRAY containing sorted time zones

=head3 DESCRIPTION

    This method returns the available timezones

=cut

#=============================================================
sub getTimeZones {
    my ($self, $from_system) = @_;

    if ($from_system and $from_system != 0) {
        require MDK::Common::DataStructure;
        require MDK::Common::Various;
        my $tz_prefix = $self->get_timezone_prefix();
        open(my $F, "cd $tz_prefix && find [A-Z]* -noleaf -type f |");
        my @l = MDK::Common::DataStructure::difference2([ MDK::Common::Various::chomp_(<$F>) ], [ 'ROC', 'PRC' ]);
        close $F or die "cannot list the available zoneinfos";
        return sort @l;
    }

    return DateTime::TimeZone->all_names;
}

#=============================================================

=head2 setTimeZone

=head3 INPUT

    $new_time_zone: New time zone to be set

=head3 DESCRIPTION

    This method get the new time zone to set and performs
    the setting

=cut

#=============================================================
sub setTimeZone {
    my ($self, $new_time_zone) = @_;

    die "Time zone value required" if !defined($new_time_zone);

    my $object   = $self->dbus_timedate1_object;
    $object->SetTimezone($new_time_zone, 1);
}

#=============================================================

=head2 getTimeZone

=head3 OUTPUT

    $timezone: current time zone

=head3 DESCRIPTION

    This method returns the current timezone setting

=cut

#=============================================================
sub getTimeZone {
    my ($self) = @_;

    my $object       = $self->dbus_timedate1_object;

    return $object->Get("org.freedesktop.timedate1", 'Timezone') || "";
}


#=============================================================

=head2 setLocalRTC

=head3 INPUT

    $enable: bool value enable/disable real time clock as
             localtime
    $fix_system: bool read or not the real time clock

=head3 DESCRIPTION

    This method enables/disables the real time clock as
    localtime (e.g. disable means set the rtc to UTC).
    NOTE from dbus:
    Use SetLocalRTC() to control whether the RTC is in
    local time or UTC. It is strongly recommended to maintain
    the RTC in UTC. Some OSes (Windows) however maintain the
    RTC in local time which might make it necessary to enable
    this feature. However, this creates various problems as
    daylight changes might be missed. If fix_system is passed
    "true" the time from the RTC is read again and the system
    clock adjusted according to the new setting.
    If fix_system is passed "false" the system time is written
    to the RTC taking the new setting into account.
    Use fix_system=true in installers and livecds where the
    RTC is probably more reliable than the system time.
    Use fix_system=false in configuration UIs that are run during
    normal operation and where the system clock is probably more
    reliable than the RTC.

=cut

#=============================================================
sub setLocalRTC {
    my ($self, $enable, $fix_system) = @_;

    die "Localtime enable/disable value required" if !defined($enable);

    $fix_system = 0 if !defined($fix_system);
    my $object   = $self->dbus_timedate1_object;
    $object->SetLocalRTC($enable, $fix_system, 1) ;
}

#=============================================================

=head2 getLocalRTC

=head3 OUTPUT

    $localRTC: 1 if RTC is localtime 0 for UTC

=head3 DESCRIPTION

    This method returns the RTC localtime setting

=cut

#=============================================================
sub getLocalRTC {
    my $self = shift;

    my $object   = $self->dbus_timedate1_object;

    return $object->Get("org.freedesktop.timedate1", 'LocalRTC') ? 1 : 0;
}

#=============================================================

=head2 setEmbeddedNTP

=head3 INPUT

    $enable: enable/disable systemd NTP service

=head3 DESCRIPTION

    This method enables/disables and starts/stops systemd NTP service,

=cut

#=============================================================
sub setEmbeddedNTP {
    my ($self, $enable) = @_;

    my $object   = $self->dbus_timedate1_object;
    $object->SetNTP(($enable ? 1 : 0), 1);
}

#=============================================================

=head2 getEmbeddedNTP

=head3 OUTPUT

    $NTP: if systemd NTP is enabled

=head3 DESCRIPTION

    This method returns the systemd NTP service is running

=cut

#=============================================================
sub getEmbeddedNTP {
    my ($self) = @_;

    my $object       = $self->dbus_timedate1_object;

    return $object->Get("org.freedesktop.timedate1", 'NTP') || "";
}




#=============================================================

=head2 setTime

=head3 INPUT

    $sec_since_epoch: Time in seconds since 1/1/1970

=head3 DESCRIPTION

    This method set the system time and sets the RTC also

=cut

#=============================================================
sub setTime {
    my ($self, $sec_since_epoch) = @_;

    die "second since epoch required" if !defined($sec_since_epoch);

    my $object = $self->dbus_timedate1_object;
    my $usec   = $sec_since_epoch* 1000000;

    $object->SetTime($usec, 0, 1);
}

#=============================================================

=head2 readConfiguration

=head3 OUTPUT

    hash reference containing:
        UTC  => HW clock is set as UTC
        ZONE => Time Zone set

=head3 DESCRIPTION

    This method returns the time zone system settings as hash
    reference

=cut

#=============================================================
sub readConfiguration {
    my $self = shift;

    my $prefs        = {};
    $prefs->{'ZONE'} = $self->getTimeZone();
    $prefs->{'UTC'}  = $self->getLocalRTC() ? 0 : 1;

    return $prefs;
}


#=============================================================

=head2 writeConfiguration

=head3 INPUT

    $info: hash containing:
           UTC  => HW clock is set as UTC
           ZONE => Time Zone

=head3 DESCRIPTION

    This method sets the passed Time Zone configuration.
    If installer_or_livecd attribute is set fix_system is
    passed to setLocalRTC

=cut

#=============================================================
sub writeConfiguration {
    my ($self, $info) = @_;

    die "UTC  field required" if !defined($info->{UTC});
    die "ZONE field required" if !defined($info->{ZONE});

    my $localRTC = $info->{UTC} ? 0 : 1;
    $self->setLocalRTC(
        $localRTC,
        $self->installer_or_livecd
    );

    $self->setTimeZone(
        $info->{ZONE}
    );
}


#left for back compatibility
sub _get_ntp_server_tree {
    my ($self, $zone) = @_;
    $zone = "-" if ! $zone;
    my $ns = $self->get_ntp_server($zone);
    return if !$ns;

    map {
        $ns->{$_} => (
             $self->get_ntp_server($_) ?
              $zone ?
                $self->loc->N($_) . "|" . $self->loc->N("All servers") :
                $self->loc->N("All servers") :
              $self->loc->N($zone) . "|" . $self->loc->N($_)
        ),
        $self->_get_ntp_server_tree($_)
    } keys %{$ns};
}

#=============================================================

=head2 ntpServers

=head3 OUTPUT

 HASHREF containing ntp_server => zone info

=head3 DESCRIPTION

 This method returns an hash ref containing pairs ntp-server, zone

=cut

#=============================================================
sub ntpServers {
    my ($self) = @_;
    # FIXME: missing parameter:
   +{$self->_get_ntp_server_tree()};
}


#=============================================================

=head2 ntpCurrentServer

=head3 INPUT

Input_Parameter: in_par_description

=head3 DESCRIPTION

Returns the current ntp server address read from configuration file

=cut

#=============================================================
sub ntpCurrentServer {
    my $self = shift;

    my $configFile = $self->ntp_configuration_file || $self->getNTPServiceConfig($self->ntp_program);

    if ($self->ntp_program eq "systemd-timesyncd") {
        return MDK::Common::Func::find { $_ ne '127.127.1.0' } map { MDK::Common::Func::if_(/^\s*NTP=\s*(\S*)\s*(\S*)/, $1) } MDK::Common::File::cat_($configFile);
    }
    else {
        return MDK::Common::Func::find { $_ ne '127.127.1.0' } map { MDK::Common::Func::if_(/^\s*server\s+(\S*)/, $1) } MDK::Common::File::cat_($configFile);
    }
}

#=============================================================

=head2 currentNTPService

=head3 DESCRIPTION

    Returns the current ntp service

=cut

#=============================================================
sub currentNTPService {
    my $self = shift;

    my $ntpd = $self->ntp_program;

    return $ntpd;
}

#=============================================================

=head2 isNTPRunning

=head3 DESCRIPTION

   This method just returns if the given ntp server is running

=cut

#=============================================================
sub isNTPRunning {
    my $self = shift;

    my $ntpd      = $self->ntp_program;
    my $isRunning = $ntpd ? $self->sh_services->is_service_running($ntpd) : 0;

    if (!$isRunning) {
        # NOTE fix systemd-timesyncd problem that prevents to set time
        if ($self->getEmbeddedNTP()) {
            $ntpd = "systemd-timesyncd";
            Sys::Syslog::syslog(
                'info|local1',
                $self->loc->N("%s enabled but stopped - disabling it",
                    $ntpd
                )
            );
            $self->setEmbeddedNTP(0);
        }
    }

    return $isRunning;
}

#=============================================================

=head2 setNTPConfiguration

=head3 INPUT

    $server: server address to be configured as NTP server

=head3 DESCRIPTION

    This method writes into NTP configuration file new server address
    settings (note that root rights are required) or it rises an
    exception

=cut

#=============================================================
sub setNTPConfiguration {
    my ($self, $server) = @_;

    my $f =  $self->ntp_configuration_file || $self->getNTPServiceConfig($self->ntp_program);;
    -f $f or return;

    die  $self->loc->N("user does not have the rights to change configuration file, skipped")
        if (!(-w $f));

    my $pool_match = qr/\.pool\.ntp\.org$/;
    my @servers = $server =~ $pool_match  ? (map { "$_.$server" } 0 .. 2) : $server;

    if ($self->ntp_program eq "systemd-timesyncd") {
        my $added = 0;
        MDK::Common::File::substInFile {
            if (/^#?\s*NTP=\s*(\S*)/ && $1 ne '127.127.1.0') {
                $_ = $added ? $_ =~ $pool_match ? undef : "#NTP=$1\n" : join(' ', 'NTP=', @servers, "\n");
                $added = 1;
            }
        } $f;
        if ($self->ntp_program eq "ntpd") {
            my $ntp_prefix = $self->ntp_conf_dir;
                MDK::Common::File::output_p("$ntp_prefix/step-tickers", join('', map { "$_\n" } @servers));
        }
    }
    else {
        my $added = 0;
        my $servername_config_suffix = $self->servername_config_suffix ? $self->servername_config_suffix : " ";
        MDK::Common::File::substInFile {
            if (/^#?\s*server\s+(\S*)/ && $1 ne '127.127.1.0') {
                $_ = $added ? $_ =~ $pool_match ? undef : "#server $1\n" : join('', map { "server $_$servername_config_suffix\n" } @servers);
                $added = 1;
            }
        } $f;
        if ($self->ntp_program eq "ntpd") {
            my $ntp_prefix = $self->ntp_conf_dir;
                MDK::Common::File::output_p("$ntp_prefix/step-tickers", join('', map { "$_\n" } @servers));
        }
    }

}

#=============================================================

=head2 enableAndStartNTP

=head3 INPUT

    $server: server address to be configured

=head3 DESCRIPTION

    This method writes into NTP configuration file new server address
    settings

=cut

#=============================================================
sub enableAndStartNTP {
    my ($self, $server) = @_;

    my $ntpd = $self->ntp_program;

    ManaTools::Shared::disable_x_screensaver();
    if ($ntpd eq "systemd-timesyncd") {
        $self->setEmbeddedNTP(1);
    }
    else {
        if ($self->isNTPRunning()) {
            $self->sh_services->stopService($ntpd);
        }

        #if systemd-timesyncd is running has to be stopped and disabled
        $self->setEmbeddedNTP(0) if ($self->getEmbeddedNTP());

        # enable but do not start the service
        $self->sh_services->set_status($ntpd, 1, 1);
        if ($ntpd eq "chronyd") {
            $self->sh_services->startService($ntpd);
            $ENV{PATH} = "/usr/bin:/usr/sbin";
            # Wait up to 30s for sync
            system('/usr/bin/chronyc', 'waitsync', '30', '0.1');
        } else {
            $ENV{PATH} = "/usr/bin:/usr/sbin";
            system('/usr/sbin/ntpdate', $server) if $server;
            $self->sh_services->startService($ntpd);
        }
    }
    ManaTools::Shared::enable_x_screensaver();
}

#=============================================================

=head2 disableAndStopNTP

=head3 DESCRIPTION

    Disable and stop the ntp server

=cut

#=============================================================
sub disableAndStopNTP {
    my $self = shift;

    my $ntpd = $self->ntp_program;

    if ($ntpd eq "systemd-timesyncd") {
        $self->setEmbeddedNTP(0);
    }
    else {
        # also stop the service without dont_apply parameter
        $self->sh_services->set_status($ntpd, 0);
    }
}

no Moose;
__PACKAGE__->meta->make_immutable;


1;