#! /usr/bin/ruby
# -*- coding: euc-jp -*-

# == 説明
# 並列計算で出力された分割データを結合したファイルが
# 存在している場合にもとの分割データファイルを消去する.
# 例えば, 
#  V.nc V_rank000000.nc V_rank000001.nc
# というファイルが存在していた場合に, V_rank000000.nc V_rank000001.nc
# を消去する.
#
# == 覚え書き
# * 消去しないほうをデフォトにするべき
# * check-merg.rb と統合するべき
#
# == オプション
# --dryrun 実際に消去はせず, ファイルリストを出力する.
#
# == 履歴
# * 2013-12-05 石渡正樹 作成

require "getoptlong"        # for option_parse

## オプション解析
parser = GetoptLong.new
parser.set_options(
                   ['--dryrun',                    GetoptLong::NO_ARGUMENT],
                   ['--help',                      GetoptLong::NO_ARGUMENT]
                   )

# 初期値
dryrun = false
help = false

parser.each_option do |name,arg|
  name.sub!(/^--/,'')
  case name
  when 'dryrun'
    dryrun = true
  when 'help' , 'h'
    help = true
  end
end

#-- help message
if (help)
  usage = "Usage: #{$0.split('/')[-1]}
    --dryrun                   dryrun (files are not removed)
    -h, --help                 show this message"
  puts usage
  exit
end

Dir::glob("*_rank000000.nc").each {|f|
  merged_file = f.gsub("_rank000000","")

  if File.exist?(merged_file) then
    splitfilepattern = f.gsub("_rank000000","_rank*")
    splitfilelist = Dir.glob(splitfilepattern)
    if (dryrun) then
      puts splitfilepattern
    else
      puts "Followings will be removed:", splitfilelist
      File.unlink *splitfilelist
    end
  end
}
