#! /usr/bin/env ruby

require 'open-uri'

#
# dump
#  dump repository
# import
#  import canna format dictionary
# clone/pull
#  get contents from remote repository
#

$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;
  print file_name + "\n"
  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_read(src_file)
  return system($backend, "--read", src_file)
end

def import_line(line, df, name)
  arr = line.split
  idx = arr.shift
  cur_wt = "#T35"
  cur_freq = 0
  order = 0;
  arr.each{|x|
    if ((x =~ /^\#/))
      tmp = x.split('*')
      cur_wt = tmp[0];
      if (tmp.length == 2)
        cur_freq = tmp[1]
      else
        cur_freq = 0
      end
    else
      order = order + 1
      #print idx + ":" + cur_wt + ":" + x + "\n"
      attr = "SRC,"+cur_wt
      attr = attr+ ","+String(cur_freq)
      attr = attr +","+String(order)+","+name
      df.write(idx + " " + x + " ? ? "+attr+" ok\n")
    end
  }
end

def do_import(src_file)
  sf = File::open(src_file)
  df = File::open("tmp-tmp", "w")
  sf.each_line{|x|
    import_line(x, df, src_file)
  }
  system($backend, "--encoding", "euc-jp", "--read", "tmp-tmp")
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")
    src_file = ARGV.shift
    do_read(src_file)
  end

  #
  if (arg == "import")
    src_file = ARGV.shift
    do_import(src_file)
  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
