# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010-2016 Nexedi SA and Contributors.
# All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is free software: you can Use, Study, Modify and Redistribute
# it under the terms of the GNU General Public License version 3, or (at your
# option) any later version, as published by the Free Software Foundation.
#
# You can also Link and Combine this program with other software covered by
# the terms of any of the Free Software licenses or any of the Open Source
# Initiative approved licenses and Convey the resulting work. Corresponding
# source of such a combination shall include the source code for all other
# software used.
#
# This program is distributed WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING file for full licensing terms.
# See https://www.nexedi.com/licensing for rationale and options.
#
##############################################################################

from __future__ import print_function
import os
import argparse
import csv

from slapos.util import mkdir_p
from slapos.collect.db import Database

def skip_bootstrap(self):
  return

Database._bootstrap = skip_bootstrap

def parseArguments():
  """
  Parse arguments for monitor collector instance.
  """
  parser = argparse.ArgumentParser()
  parser.add_argument('--output_folder',
                      help='Path of the folder where output files should be written.')
  parser.add_argument('--collector_db',
                      default='/srv/slapgrid/var/data-log/',
                      help='The path of slapos collect database is located.')

  return parser.parse_args()

def writeFile(name, folder, date_scope, rows):
  folder = os.path.join(folder, date_scope)
  f = os.path.join(folder, "dump_%s.csv" % name)
  if os.path.exists(f):
    # File already exists, no reason to recreate it.
    return
  mkdir_p(folder, 0o755)
  with open(f, "w") as file_io:
    csv.writer(file_io).writerows(rows)

def dump_table_into_csv(db, folder):
    db.connect()
    table_list = db.getTableList()
    # Save all dates first, as db.selector may switch the cursor
    date_list = [(date_scope, _) \
       for date_scope, _ in db.getDateScopeList(reported=1)]

    for date_scope, amount in date_list:
      for table in table_list:
        if os.path.exists(
            os.path.join(folder, "%s/dump_%s.csv" % (date_scope, table))):
          # File already exists, no reason to recreate it.
          continue
        writeFile(table, folder, date_scope, 
              db.select(table, date_scope))
    db.close()


if __name__ == "__main__":
  parser = parseArguments()
  if parser.output_folder is None:
    raise Exception("Invalid ouput folder: %s" % parser.output_folder)
  
  if parser.collector_db is None:
    raise Exception("Invalid collector database folder: %s" % parser.collector_db)
  
  
  if not os.path.exists(parser.output_folder) and \
          os.path.isdir(parser.output_folder):
    raise Exception("Invalid ouput folder: %s" % parser.output_folder)

  
  if not os.path.exists(parser.collector_db):
    print("Collector database not found...")

  dump_table_into_csv(Database(parser.collector_db), parser.output_folder)
