#!/bin/perl

#
# This program adds a vect file in ./vects to the corresponding tar in .tars, starting a new tar if needed.
# The resulting file is checked into svn (if it's a new knot type), and the vect is removed.
#

use strict;
use warnings;
use File::Slurp;
use File::Spec;
use File::Copy;
use File::Path;
use Data::Dumper;
use Cwd;

require './bin/tightknot_common.pl';

print STDERR "addFile.pl 1.0. Adds a VECT file or files to the correct tar or tars.\n";

my $cwd;
$cwd = getcwd;

my @files;
@files = @ARGV;

my $thisfile;
my $file;
my $directories;
my $volume;
my $knot_type;
my $tag;

FILE: foreach $thisfile (@files) {

  unless (-f $thisfile) {

    if (-f "$cwd/vects/$thisfile") {

      $thisfile = "$cwd/vects/$thisfile";
      print "Found $thisfile in ./vects.\n";

    } else {

      print "Couldn't find $thisfile.\n";
      next FILE;

    }

  } else {

    print "Found $thisfile.\n";
    $thisfile = "$cwd/$thisfile";

  }

  # At this point, $thisfile contains a valid filename. We try to parse it.

  ($volume,$directories,$file) = File::Spec->splitpath( $thisfile );
 
  # The string $file should contain the base filename. We now try to parse it into knot type and tag.

  unless ($file =~ /(.+)\_(.+)\.vect/) { die ("Couldn't parse vect name $file.\n"); }

  $knot_type = $1;
  $tag = $2;

  print "Parsed $file into knottype $knot_type and tag $tag.\n";

  # Now we look for the tar file.

  chdir("$cwd/tars/") or die("Couldn't change working directory to $cwd/tars");

  if (-f "${knot_type}.tar.gz") {

    print "Adding file to matching TAR file ${knot_type}.tar.gz\n";
    `tar  -xzf ${knot_type}.tar.gz`;
    unless (-f "./${knot_type}/${knot_type}_${tag}.vect") {
      copy($thisfile,"./${knot_type}/${knot_type}_${tag}.vect") or die("Couldn't copy $thisfile to /tars/${knot_type}/${knot_type}_${tag}.vect");
      `tar -czf $cwd/tars/${knot_type}.tar.gz ./${knot_type}/`;   
    } else {
      warn("File $thisfile is already present in archive! Skipping this add.\n");
    }

  } else {

    print "Creating NEW tar file ${knot_type}.tar.gz (will add to svn).\n";
    mkdir "./${knot_type}" or die("Couldn't make /tars/${knot_type}");
    copy($thisfile,"./${knot_type}/${knot_type}_${tag}.vect") or die("Couldn't copy $thisfile to /tars/${knot_type}/${knot_type}_${tag}.vect");
    `tar -czf $cwd/tars/${knot_type}.tar.gz ./${knot_type}/`;
    `svn add ${knot_type}.tar.gz`;
    
  }

  rmtree("./${knot_type}/") or die("Couldn't remove ${knot_type}/ \n");
  chdir("$cwd") or die("Couldn't change directory back to $cwd.\n");

  # Now we remove the original file.

  `svn rm --quiet $thisfile 2>&1`;
  unlink($thisfile);
  
}

