# -*- coding: utf-8 -*-
#
# UnivNautes
# Copyright (C) 2014  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 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 Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.core.management.base import BaseCommand, CommandError
import os
from sp import pfconfigxml

WHITELISTS_DIR = os.path.join('/', 'var', 'tmp', 'univnautes-sp-whitelists')

class Command(BaseCommand):
    help = 'dump whitelists info in %s' % WHITELISTS_DIR

    def handle(self, *args, **options):
        if os.path.exists(WHITELISTS_DIR):
            print "error: %s already exists" % WHITELISTS_DIR
            return
        os.mkdir(WHITELISTS_DIR, 0770)
        whitelists = pfconfigxml.get_whitelists()
        for whitelist in whitelists:
            refid = whitelist.get('id')
            url = whitelist.get('url')
            codename = whitelist.get('codename')
            cacert = whitelist.get('cacert')
            wldir = os.path.join(WHITELISTS_DIR, refid)
            os.mkdir(wldir)
            conf_filename = os.path.join(wldir, 'conf.sh')
            with open(conf_filename, 'w') as f:
                f.write('URL="%s"\n' % url)
                f.write('CODENAME="%s"\n' % codename)
            if cacert:
                cacert_filename = os.path.join(wldir, 'cacert.pem')
                with open(cacert_filename, 'w') as f:
                    f.write(cacert)
