#!/usr/bin/python3

import argparse
import logging
import os
import sys

from grove import become as grove_become
from grove import config as grove_config
from grove import util

def main():
  parser = argparse.ArgumentParser(description='Become a service.')
  parser.add_argument('--yaml', metavar='file', type=str, help='path to service.yaml')
  parser.add_argument('--type', metavar='type', type=str, help='service type, needed when using --yaml')
  parser.add_argument('--hash', metavar='hash', type=str, help='hash of previously deployed service')
  parser.add_argument('-c', '--post-deploy-commands', metavar='command', action='append',
                      help='commands run before services are activated')
  parser.add_argument('--always-bounce', action='store_true', help='bounce services even if nothing has changed')
  parser.add_argument('--skip-start', action='store_true', help='skip starting services')
  parser.add_argument('--syslog', metavar='syslog', type=str,
                      help='Comma-delimited list of services that will send logs to syslog (UDP 514)')
  parser.add_argument('--debug', action='store_true', help='use debug logging')
  parser.add_argument('--post-deploy-commands-timeout', type=int, metavar='command_timeout',
                      help='Timeout for post-deploy-commands in seconds', default=300)
  parser.add_argument('--log-file', type=str, metavar='log_file', help='File to which logs are produced')
  args = parser.parse_args()

  if (not args.yaml and not args.hash) or (args.yaml and (args.hash or not args.type)):
    sys.stderr.write("usage: \"become --yaml file --type type\" or \"become --hash hash\"\n")
    sys.exit(1)

  config = grove_config.load_config()

  debug = args.debug or config.get('debug', False)

  if args.log_file is not None:
    logging.basicConfig(
      format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
      level=logging.DEBUG if debug else logging.INFO,
      filename=args.log_file
    )
  else:
    logging.basicConfig(
      format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
      level=logging.DEBUG if debug else logging.INFO
    )

  if args.yaml:
    service_yaml, service_yaml_sha1 = grove_config.load_yaml_file_with_sha1(args.yaml)
    service_type = args.type
    pulled = util.asyncio_run(
      grove_become.become(config, service_yaml, service_type, args.post_deploy_commands, args.always_bounce, args.skip_start,
                          args.syslog, args.post_deploy_commands_timeout))
  else:
    pulled = util.asyncio_run(
      grove_become.become_prior(config, args.hash, args.post_deploy_commands, args.always_bounce, args.skip_start, args.syslog,
                                args.post_deploy_commands_timeout))

  sys.stderr.write('activate: {}\n'.format(os.path.basename(pulled)))
  sys.stderr.flush()

main()
sys.exit(0)
