#!/usr/pkg/bin/perl
# $Id: split.pl,v 1.8 2000/10/01 14:30:28 tom Exp $
#
# split.pl : 月まとめ tdf を日毎に分割する
# option:
#   -f             強制（新しくなくとも分割）
#   -c             CGI モード
#   -y year        年指定
#   -m month       月指定
#   -q             静かモード
################################################################

use strict;
use lib qw(lib);
use Getopt::Std;
use File::Path;    # mkpath()

use TDS;
use TDS::System;
use TDS::DirInfo;

################################################################
my %opt;
my ($year, $month, $day);
my @orig_files;

getopts("afcy:m:q", \%opt);

my $cgi_mode = $ENV{'REQUEST_URI'} || $opt{'c'};
if ($cgi_mode){
    $opt{q} = 1;
    $opt{t} = 1;
    print "content-type: text/html\n";
}

my $diary_dir = $TDS::DirInfo::DiaryDir;

my $now_year = $opt{y} || (localtime)[5]+1900;
my $now_month = $opt{m} || (localtime)[4]+1;
my $now_day = (localtime)[3];

if ($opt{a}){     # 全て
    my $status = new TDS::Status;
    my $now_year = (localtime)[5]+1900;
    for ($status->start_year..$now_year){
	my $year = $_;
	my $dir = "$diary_dir/$year";
	opendir(DIR, $dir) || next;
	for (sort readdir(DIR)){
	    next unless /^(\d\d)\.tdf$/;
	    push(@orig_files, "$diary_dir/$year/$_");
	}
    }
} else {
    push(@orig_files, sprintf("%s/%04d/%02d.tdf",
			      $diary_dir,
			      $now_year, $now_month));
}
			      
# すべてのファイル
my $write;
for (@orig_files){
    open(IN, $_) || die $_;
    my $lm = (stat($_))[9];
    print "orig:$_\n" unless $opt{q};
    while (<IN>){
#	print $_;
	s/\r\n$/\n/;
	if (/^DIARY +(\d{4}) +(\d{2}) +(\d{2})$/){   # 日付の区切り
	    ($year, $month, $day) = ($1, $2, $3);
	    my $path = "$diary_dir/$year/$month/$day.tdf";
	    
	    $write = $opt{f} || ($lm > (stat($path))[9]);
	    unless ($opt{q}){
		if ($write){
		    print "$path";
		} else {
		    print "($path)";
		}
		print "\n";
	    }
	    close F;
	    if ($write){
		unless (-d "$diary_dir/$year/$month"){
		    mkpath("$diary_dir/$year/$month", 0, 0755);
		}
		open(F, ">$path") || die $path;
	    }
	} else {
#	    &jcode::convert(*_, 'euc');
	    print F $_ if $write;
	}
    }
    close F;
}

if ($cgi_mode){
    print "location: $TDS::System::DiaryURL\n\n";
}


