#!/usr/bin/perl -w

use Debconf::Client::ConfModule qw(:all);

###############################################################################
# Stolen from debhelper(1)

my $temp="set -e\nset -- @ARGV\n" . << 'EOF';
if [ "$1" = "configure" ]; then
    [ -x /usr/sbin/update-configlets ] && /usr/sbin/update-configlets
fi

#DEBHELPER#
EOF

system ($temp) / 256 == 0
  or die "Problem with debhelper scripts: $!";

###############################################################################

my $toplevel = get("timezoneconf/toplevel");
my $zone = get("timezoneconf/zone");

# If /etc/localtime exists and is a link, dereference it no matter what.

if (-l "/etc/localtime") {
  # print STDERR "Detected link, dereferencing.\n";
  system("/bin/cp --dereference /etc/localtime /etc/localtime.save");
  system("/bin/rm -f /etc/localtime");
  system("/bin/mv /etc/localtime.save /etc/localtime");
}

# Bail if they haven't been answered yet!

unless ((fget("timezoneconf/toplevel", "isdefault") eq "false") &&
	(fget("timezoneconf/zone", "isdefault") eq "false")) {
  # print STDERR "Not setting zone; question not answered.\n";
  exit(0);
}

unless ($toplevel && $zone) {
  # print STDERR "Not setting zone, info not entered.";
  exit 0;
}

open TZFILE, ">/etc/timezone";
print TZFILE "$toplevel/$zone\n";

# print STDERR "Wrote new timezone \"$toplevel/$zone\" to /etc/timezone\n";

unlink("/etc/localtime");

# print STDERR "Linking /etc/localtime -> /usr/share/zoneinfo/$toplevel/$zone\n";

unlink("/etc/localtime");
system("/bin/cp /usr/share/zoneinfo/$toplevel/$zone /etc/localtime");

