#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: set expandtab:tabstop=4:softtabstop=4:shiftwidth=4
# $Id$

import argparse
import os
import subprocess
import sys
import yaml
import hashlib

def run():
    default_vhosts_config = '/etc/yandex-direct/direct-vhosts.yaml'
    desc=u'''
    # положить сертификаты для intapi.direct.yandex.ru по путям из {default_vhosts_config}
    dt-place-certs --vhost intapi.direct.yandex.ru --yav-oauth-file /etc/direct-tokens/yav_robot-direct-yav-p

    # если какие-то сертификаты там уже есть, по умолчанию он не перезапишутся, нужно указать --force
    dt-place-certs --vhost intapi.direct.yandex.ru --yav-oauth-file /etc/direct-tokens/yav_robot-direct-yav-p --force

    # можно указать другой конфиг
    dt-place-certs --vhost intapi.direct.yandex.ru --yav-oauth-file /etc/direct-tokens/yav_robot-direct-yav-p --vhosts-config my-vhosts.yaml
'''.format(default_vhosts_config=default_vhosts_config)
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=desc)
    parser.add_argument('--vhosts-config', default=default_vhosts_config)
    parser.add_argument('--vhost', required=True)
    parser.add_argument('--force', action='store_true')
    parser.add_argument('--yav-oauth-file', required=True)
    args = parser.parse_args()
    vhost = args.vhost
    vhosts_config = yaml.load(open(args.vhosts_config, 'r'))['vhosts']
    if vhost not in vhosts_config:
        sys.exit('error: unknown vhost ' + vhost)
    if 'ssl_certs' not in vhosts_config[vhost]:
        sys.exit('error: no certificates in config for vhost ' + vhost)
    certs = vhosts_config[vhost]['ssl_certs']
    existing_paths = [x['path'] for x in certs if os.path.exists(x['path'])]
    for cert in vhosts_config[vhost]['ssl_certs']:
        content = subprocess.check_output(['/usr/local/bin/dt-yav', '--yav-oauth-file', args.yav_oauth_file, 'cat', cert['secret_id'] + ':' + cert['secret_key']])
        if cert['path'] in existing_paths: 
            if hashlib.md5(open(cert['path'], 'rb').read()).hexdigest() == hashlib.md5(content).hexdigest():
                print("File %s equal file from yav with md5 %s" % (cert['path'], hashlib.md5(content).hexdigest()))
                existing_paths.remove(cert['path'])
                continue
            elif args.force:
                print("Replace %s by content from yav" % cert['path'])
                existing_paths.remove(cert['path'])
            else:
                continue
        f = open(cert['path'], 'w+')
        # пока нет необходимости перезаписывать существующий файл атомарно: после привоза новых файлов всё равно перезапускаем nginx вручную
        f.write(content)
    if existing_paths and not args.force:
        sys.exit('some of the certificate files already exist:\n  ' + '\n  '.join(existing_paths) + ' and differ from yav\n\nExiting. Use --force to overwrite.')


if __name__ == '__main__':
    run()

