#! /usr/bin/perl -w

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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

use utf8;
use encoding 'utf8';
use open ':utf8'; # input and output default layer will be UTF-8
use POSIX;

sub is_yes($) {
  my $question=shift;
  print $question;
  my $yn=<>;
  chomp $yn;
  if ($yn ne "y" and $yn ne "Y") {return 0}
  return 1;
}

sub sure($) {
  $q=shift;
  if (not is_yes("$q")) {print"Aborted!\n"; exit(-1)}
}
sub cd_th {
  my $pwd=getcwd();
  do {
    if (-d "+") {return $pwd;}
    chdir("..");
    $pwd=getcwd();
  }until ($pwd eq "/");
  return 0;
}

my $prefix;
my $title;
my $fn="../file.tar.bz2";
my $F="+/0";
$prefix=cd_th() or die "Could not found Thwab control + directory";
printf "@<%s>\n",$prefix;
open F, "<$F" or die "no control file [$F]";
while(<F>) {
  if (/^\s*thwab\s*=\s*(.*)\s*$/) {
    $title=$1;
    $fn="../$1.tar.bz2";
    last
  }
}
close F;
printf "Filename [$fn]\n";
if ( -f $fn) { sure("File [$fn] exists! Overwrite? (y/N): "); }
$s4="../$title.4";
if ( -f "+/4") {
  printf "Search cache found\n";
  if ( -f $s4 ) {
    sure("Search cache [$s4] exists! Overwrite? (y/N): ");
  }
  rename "+/4", "$s4" or die "could not move search cache to parent folder";
} else {
  printf "Search cache was not found!!\a\n";
}
system "itar", "-c", "$fn",".";
if (-f $s4) {
if (is_yes("Compress search cache [$s4] ? (y/N): ")) {
  print "gzip -9 <\"$s4\" >\"$s4.gz\"\n";
  system ("gzip -9 < \"$s4\" > \"$s4.gz\"");
  rename "$s4", "+/4" or die "could not move search cache back to control";
} else {
system ("cp", "$s4", "+/4")
}
}
