#! /usr/bin/env ruby

require 'open-uri'

$backend="fossil-backend";

def dump()
  r = system($backend, "--dump");
  if (!r)
    print "Command Failed\n";
  end
end

def do_merge(target_uri, path)
  file_name = target_uri+"/words/"+ path;
  open(file_name) do |f|
    words = f.read
    wf = File.open("tmp-tmp", "w");
    wf.write(words);
    wf.close;
    return system($backend, "--encoding", "utf8", "--read", "tmp-tmp");
  end
end

def do_clone(target_uri)
  r = true;
  open(target_uri +"/index") do |f|
    index = f.read
    index.each_line{|s|
      if (s =~ /(\w+) (\w+) (\w+)/)
        if (Integer($2) > 0)
          r = do_merge(target_uri, $1);
          if (!r)
            print "Command Failed\n";
          end
        end
      end
    }
  end
  system($backend, "--encoding", "utf8", "--update-index");
end

while arg = ARGV.shift
  if (arg == "dump")
    dump
  end
  if (arg == "read")
  end
  if (arg == "clone" || arg == "pull")
    target_uri = ARGV.shift
    if (target_uri)
      do_clone(target_uri)
    else
      print "please specify target\n";
      exit 1;
    end
  end
end
