#!/opt/csw/bin/python2.6

"""A utility to create test data files on disk.

To use an existing md5 sum in a file to refresh it:

lib/python/prepare_test_data.py \
    --md5 $(cat lib/python/testdata/ivtools_stats.py \
            | tr "'" '\n' | egrep '[0-9a-f]{32}')

"""

import optparse
import pprint
import logging
import pipes
import sys

from lib.python import configuration
from lib.python import rest
from lib.python import errors


def main():
  parser = optparse.OptionParser()
  parser.add_option("-c", "--catalogname", dest="catalogname")
  parser.add_option("--catalog-release", dest="catrel", default="kiel")
  parser.add_option("--arch", dest="arch", default="sparc")
  parser.add_option("--os-release", dest="osrel", default="SunOS5.9")
  parser.add_option("--md5", dest="md5")
  parser.add_option("--debug", dest="debug", default=False, action="store_true")
  options, args = parser.parse_args()
  if options.debug:
    logging.basicConfig(level=logging.DEBUG)
  else:
    logging.basicConfig(level=logging.INFO)
  config = configuration.GetConfig()
  rest_client = rest.RestClient(
      pkgdb_url=config.get('rest', 'pkgdb'),
      releases_url=config.get('rest', 'releases'))
  if options.md5:
    md5 = options.md5
  else:
    pkg_basic = rest_client.Srv4ByCatalogAndCatalogname(
        options.catrel, options.arch, options.osrel, options.catalogname)
    md5 = pkg_basic["md5_sum"]
  logging.info("Fetching %s", md5)
  pkgstats = rest_client.GetBlob('pkgstats', md5)
  # getting elfdump info
  elfdump_data = {}
  for _, binary_md5 in pkgstats["binary_md5_sums"]:
    elfdump_data[binary_md5] = rest_client.GetBlob('elfdump', binary_md5)
  catalogname = pkgstats["basic_stats"]["catalogname"]
  target_file = "lib/python/testdata/%s_stats.py" % catalogname
  pkgstats['elfdump_info'] = elfdump_data
  with open(target_file, "wb") as fd:
    fd.write("# Generated by running:\n")
    fd.write("# %s\n\n" % ' '.join(pipes.quote(x) for x in sys.argv))
    fd.write("pkgstats = [")
    fd.write(pprint.pformat(pkgstats))
    fd.write("]\n\n")
  print target_file, "done"


if __name__ == '__main__':
  main()
