#/usr/bin/python
import sys
import os

def split_stream(stream_sql_file, outputdir):
  stream_fd = open(stream_sql_file, 'r')
  lines = stream_fd.readlines()
  count = 0
  need_new_file = False
  output_fd = None
  for line in lines:
    if line.strip().startswith("-- start query"):
      need_new_file = True
      #continue
    if need_new_file:
      if output_fd:
        output_fd.close()
      count+=1
      need_new_file = False
      output_fd = open(outputdir + '/query%d.sql' % count, 'w')
    output_fd.write(line)
  if output_fd:
    output_fd.close()

if __name__ == '__main__':
  if len(sys.argv) != 3:
    print "error param, python split.py [stream_sql_file] [outputdir]"
    sys.exit(1)
  stream_sql_file = sys.argv[1]
  output_dir = sys.argv[2]
  if os.path.isfile(output_dir):
    print 'output_dir:%s is a file' % output_dir
    sys.exit(1)
  if not os.path.exists(output_dir):
    os.makedirs(output_dir)
  if not os.path.isfile(stream_sql_file):
    print 'stream_sql_file:%s is not a file' % stream_sql_file
    sys.exit(1)
  split_stream(stream_sql_file, output_dir)
