# -*- coding: utf-8 -*-
# vim: set et sts=2:

import ConfigParser
import datetime
import flask
import logging
import logging.handlers
import os
import argparse
import traceback
from slapos.certificate_authority.certificate_authority import CertificateAuthorityRequest

def parseArguments():
  """
  Parse arguments for monitor instance.
  """
  parser = argparse.ArgumentParser()
  parser.add_argument('--cert_file',
                      default='cert.pem',
                      help='Path for Certificate file')
  parser.add_argument('--ca_cert_file',
                      default='cacert.pem',
                      help='Path for CA Cert file.')
  parser.add_argument('--key_file',
                      default='key.pem',
                      help='Path of key file')
  parser.add_argument('--csr_file',
                      default='csr.pem',
                      help='Path where to store csr file.')
  parser.add_argument('--ca_url',
                      help='Certificate Authority URL')
  parser.add_argument('--cn',
                      help='Common name to use in certificate request')
  parser.add_argument('--country',
                      default='XX',
                      help='Country Name')
  parser.add_argument('--state',
                      default="(State,)",
                      help='State Name')
  parser.add_argument('--locality',
                      default='City',
                      help='City or Locality Name')
  parser.add_argument('--email',
                      default='xx@example.com',
                      help='The email to use')
  parser.add_argument('--organization',
                      default='Company',
                      help='The Organisation Name')
  parser.add_argument('--organization_unit',
                      default='Company Unit',
                      help='The Organisation Unit Name')

  return parser.parse_args()


def requestCertificateWeb():

  config = parseArguments()

  ca = CertificateAuthorityRequest(config.key_file, config.cert_file,
          config.ca_cert_file, config.ca_url)

  ca.getCACertificateWeb()

  if os.path.exists(config.cert_file):
    # XXX- should check later if the certificate is expired
    return

  # When renew certificate, another verification can be done
  if not os.path.exists(config.csr_file):
    ca.generateCertificateRequest(config.key_file, config.csr_file,
        cn=config.cn, country=config.country, state=config.state,
        locality=config.locality, email=config.email,
        organization=config.organization,
        organization_unit=config.organization_unit, digest="sha1")

  ca.signCertificateWeb(config.csr_file)

