#!/usr/bin/perl

use strict;
use warnings;

my $repository = "/usr/local/data/ktug/ftp.ktug.org/KTUG/texlive/tlnet";

my $logfile = "ChangeLog.tlnet";
my $dbfile = "tlpkg/texlive.tlpdb";

my $readtree = 0;
my %package;

sub printusage {
    print "Usage:  $0 [-updatedb] <package> ...\n";
    print "      --updatedb : when new file(s) added, or .tlpsrc has changed.\n";
    print "      <package> may include `.ARCH', which expands to architecture names.\n";
    exit 0;
}

printusage() unless @ARGV;

for (@ARGV) {
  if (/\-h/) {
	printusage()
  }
  elsif (/\-(updatedb|readtree)/) {
    $readtree = 1;
  }
  elsif (/(.+)\.ARCH/) {
    my $prefix = $1;
    opendir(my $dh, "bin") or die;
    my @dirs = grep{/^[^\.]/ and -d "bin/$_"} readdir($dh);
    closedir $dh;
    for (@dirs) {
      $package{"$prefix\.$_"} = 1000;
    }
  }
  else {
    $package{$_} = 1000;
  }
}

my %tlpdb;
my $name = 0;
open my $fh, $dbfile or die;
while(<$fh>) {
  if (/^name\s+([\w\.\-]+)/) {
    $name = $1;
  }
  elsif (/^revision\s+(\d+)/) {
    $tlpdb{$name} = $1;
    $tlpdb{$name}++ if $package{$name};
  }
}
close $fh;

printf "To be updated:\n";
for (keys %package) {
  if ($tlpdb{$_}) {
    printf "\t%-24s => %6d\n",$_,$tlpdb{$_};
  }
  else {
    $tlpdb{$_} = $package{$_};
    printf "\t%-24s => %6d (new)\n",$_,$tlpdb{$_};
  }
}
$readtree ?  print "WITH" : print "WITHOUT";
print " DB UPDATE. Really proceed? [y/N] ";
my $userinput = <STDIN>;
exit 0 unless $userinput =~ /^y/i;

if ($readtree) {
  system ("perl", "tlpkg/bin/tl-update-tlpdb",
    "-from-files", "-no-reverse-revision-check"); 
  $? >> 8 and die;
}

my @lines;
open $fh, $dbfile or die;
while(<$fh>) {
  if (/^name\s+([\w\.\-]+)/) {
    $name = $1;
    push @lines, $_;
  }
  elsif ($name and $tlpdb{$name} and /^revision\s+(\d+)/) {
    push @lines, "revision $tlpdb{$name}\n";
  }
  else {
    push @lines, $_;
  }
}
close $fh;

open $fh, ">", $dbfile or die;
print $fh @lines;
close $fh;

if ($readtree) {
  system("less",$dbfile);
  print "Really proceed? [y/N] ";
  $userinput = <STDIN>;
  exit 0 unless $userinput =~ /y/i;
}

system ("perl", "tlpkg/bin/tl-update-containers",
  "-location", $repository, "-no-setup", # "-no-relative",
  "-gpgcmd", "/home/nomos/ktugrepo/tl-sign-file");
$? >> 8 and die;

my ($sec, $min, $hour, $mday, $mon, $year) = localtime;
my @LOG = (sprintf("%04d-%02d-%02d %02d:%02d\n\n",
		$year+1900, $mon+1, $mday, $hour, $min));

open $fh, $logfile or die;
push @LOG, <$fh>;
close $fh;

open $fh, ">", $logfile or die;
print $fh @LOG;
close $fh;

#####
# 연도 업데이트:
#
# 개별 패키지를 업데이트할 것이 있으면 다 한 다음,
# 00texlive.config.tlpsrc 파일과 texlive.tlpbd 파일에서 연도를 바꾸고 
#
# perl tlpkg/bin/tl-update-containers \
# -location /usr/local/data/ktug/ftp.ktug.org/KTUG/texlive/tlnet \
# -no-setup -gpgcmd /home/nomos/ktugrepo/tl-sign-file
#
