#!/usr/bin/python2

import json
import os
import sys
from os.path import join as join_path
SETUPSTORE_VPN_PROFILE_DIRPATH = '/etc/edge/setupstore/admin/actions/vpn-profile/'
ETC_OPENVPN_DIRPATH = '/etc/openvpn/'


def write_text_file(file_abspath, file_content):
    with open(file_abspath, 'w') as destination_file:
        destination_file.write(file_content)


def get_profile_jnode(profile_guid):
    """
    :type profile_guid: str
    :rtype: dict | None
    """
    profile_jnode_abspath = SETUPSTORE_VPN_PROFILE_DIRPATH + profile_guid + '.json'
    if os.path.exists(profile_jnode_abspath):
        with open(profile_jnode_abspath, 'r') as old_jnode_file:
            profile_jnode = json.load(old_jnode_file)
            return profile_jnode

    return None


def edit_certificates(profile_guid, new_jnode):
    ca_cert_abspath = ETC_OPENVPN_DIRPATH + profile_guid + '.ca'
    client_cert_abspath = ETC_OPENVPN_DIRPATH + profile_guid + '.cert'
    client_key_abspath = ETC_OPENVPN_DIRPATH + profile_guid + '.key'

    ca_cert_content = new_jnode['ca-cert']
    client_cert_content = new_jnode['client-cert']
    client_key_content = new_jnode['client-key']

    #
    if ca_cert_content:
        write_text_file(ca_cert_abspath, ca_cert_content)

    elif not ca_cert_content and os.path.exists(ca_cert_abspath):
        old_jnode = get_profile_jnode(profile_guid)
        ca_cert_content = old_jnode['ca-cert']
        write_text_file(ca_cert_abspath, ca_cert_content)

    else:
        ca_cert_abspath = None

    #
    if client_cert_content:
        write_text_file(client_cert_abspath, client_cert_content)

    elif not client_cert_content and os.path.exists(client_cert_abspath):
        old_jnode = get_profile_jnode(profile_guid)
        client_cert_content = old_jnode['client-cert']
        write_text_file(client_cert_abspath, client_cert_content)

    else:
        client_cert_abspath = None

    #
    if client_key_content:
        write_text_file(client_key_abspath, client_key_content)

    elif not client_key_content and os.path.exists(client_key_abspath):
        old_jnode = get_profile_jnode(profile_guid)
        client_key_content = old_jnode['client-key']
        write_text_file(client_key_abspath, client_key_content)

    else:
        client_key_abspath = None

    return ca_cert_abspath, client_cert_abspath, client_key_abspath


def edit_vpn_profile_conf(profile_guid, new_jnode):
    profile_conf_lines = ['\n# mandatory\nclient\nuser nobody\ngroup nogroup\nverb 3\n'
                          'log /var/log/openvpn.log\nstatus /var/log/openvpn-status.log\n#']

    interface = new_jnode['interface']
    profile_conf_lines.append('\ndev %s\n' % interface)

    if new_jnode['compression']:
        profile_conf_lines.append('comp-lzo\n')

    server_host = new_jnode['server-host']
    server_port = new_jnode['server-port']
    profile_conf_lines.append('remote %s %s\n' % (server_host, server_port))

    prototcol = new_jnode['protocol']
    profile_conf_lines.append('\nproto %s\n' % prototcol)

    ca_cert_abspath, client_cert_abspath, client_key_abspath = edit_certificates(profile_guid, new_jnode)

    if ca_cert_abspath is not None:
        profile_conf_lines.append('ca %s\n' % ca_cert_abspath)

    if client_cert_abspath is not None:
        profile_conf_lines.append('cert %s\n' % client_cert_abspath)

    if client_key_abspath is not None:
        profile_conf_lines.append('key %s\n' % client_key_abspath)

    mtu_size = new_jnode['mtu-size']
    cipher = new_jnode['cipher']
    hmac = new_jnode['hmac']
    profile_conf_lines.append('tun-mtu %s\ncipher %s\nauth %s\n' % (mtu_size, cipher, hmac))

    profile_conf_abspath = ETC_OPENVPN_DIRPATH + profile_guid + '.conf'
    with open(profile_conf_abspath, 'w') as profile_conf_file:
        profile_conf_file.write(''.join(profile_conf_lines))

if not os.path.exists(SETUPSTORE_VPN_PROFILE_DIRPATH):
    sys.exit(0)

vpn_profiles_file_names = os.listdir(SETUPSTORE_VPN_PROFILE_DIRPATH)

for vpn_profile_file_name in vpn_profiles_file_names:
    vpn_profile_path = join_path(SETUPSTORE_VPN_PROFILE_DIRPATH, vpn_profile_file_name)

    with open(vpn_profile_path, 'r') as old_jnode_file:
        profile_jnode = json.load(old_jnode_file)

    old_to_new_names = {
        "SHA-1": "SHA1",
        "SHA-224": "SHA224",
        "SHA-256": "SHA256",
        "SHA-384": "SHA256",
        "SHA-512": "SHA512"
    }

    old_vpn_profile = profile_jnode['hmac']
    new_vpn_profile = old_to_new_names.get(old_vpn_profile)

    if new_vpn_profile is not None:
        profile_jnode['hmac'] = new_vpn_profile

    edit_vpn_profile_conf(profile_jnode['id'], profile_jnode)

    with open(vpn_profile_path, 'w') as json_file:
        json.dump(profile_jnode, json_file, indent=2)
