#!/usr/bin/env python
# -*- coding: utf-8 -*-
# +--------------------------------------------------------------------------+
# | Endian Firewall                                                          |
# +--------------------------------------------------------------------------+
# | Copyright (c) 2004-2016 S.p.A. <info@endian.com>                         |
# |         Endian S.p.A.                                                    |
# |         via Pillhof 47                                                   |
# |         39057 Appiano (BZ)                                               |
# |         Italy                                                            |
# |                                                                          |
# | This program is free software; you can redistribute it and/or modify     |
# | it under the terms of the GNU General Public License as published by     |
# | the Free Software Foundation; either version 2 of the License, or        |
# | (at your option) any later version.                                      |
# |                                                                          |
# | This program is distributed in the hope that it will be useful,          |
# | but WITHOUT ANY WARRANTY; without even the implied warranty of           |
# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            |
# | GNU General Public License for more details.                             |
# |                                                                          |
# | You should have received a copy of the GNU General Public License along  |
# | with this program; if not, write to the Free Software Foundation, Inc.,  |
# | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.              |
# +--------------------------------------------------------------------------+

import os
from endian.data import DataSource
from endian.core.pdict import PersistentDict


def getVPNServers():
    """Return the list of enabled VPN server."""
    pd = PersistentDict('/var/cache/var.efw.vpn.servers')
    ret = []
    servers = DataSource('openvpn').server or []
    for server in servers:
        if not server.get('enabled'):
            continue
        sdict = dict(server)
        sdict['interfaces'] = pd.get(server.get('ID'), {}).get('purple_devices') or []
        ret.append(sdict)
    return ret


def buildCSV(servers):
    """Return a CSV string with the given servers, following the schema:
        id,serverName,device1[|device2...],bridged,bridgeZone"""
    lines = ['%s,%s,%s,%s,%s' % (x.get('id'), x.get('name'),
                            '|'.join(x.get('interfaces')),
                            x.get('bridged'),
                            x.get('bridge_to')
                            ) for x in servers]
    return os.linesep.join(lines)


if __name__ == '__main__':
    print buildCSV(getVPNServers())

