# Path: upribox_interface/vpn/forms.py
# class VpnProfileForm(forms.Form):
# 
#     profilename = forms.CharField(
#         required=True,
#         label=ugettext_lazy("Name:"),
#         max_length=64,
#     )
# 
#     dyndomain = forms.CharField(
#         required=True,
#         label=ugettext_lazy("Domain:"),
#         max_length=64,
#     )
# 
#     def __init__(self, *args, **kwargs):
#         super(VpnProfileForm, self).__init__(*args, **kwargs)
# 
#         upri_dns_domain = None
# 
#         try:
#             upri_dns_domain = get_fact('dns', 'dns', 'hostname')
#         except:
#             logger.error('Kein upri DNS fact gefunden.')
# 
#         if upri_dns_domain:
#             self.fields['dyndomain'].widget = forms.HiddenInput()
#             self.fields['dyndomain'].initial = upri_dns_domain
#             self.fields['dyndomain'].label = ""
# 
#     def clean_profilename(self):
#         profilename = self.cleaned_data['profilename']
#         try:
#             VpnProfile.objects.get(profilename=profilename)
#             raise forms.ValidationError(ugettext_lazy("Profil existiert bereits"))
#         except VpnProfile.DoesNotExist:
#             return profilename
# 
#     def clean_dyndomain(self):
# 
#         dyndomain = self.cleaned_data['dyndomain']
# 
#         errors = []
#         check = domain.Domain(dyndomain)
# 
#         if not check.is_valid():
#             if not check.has_allowed_length():
#                 errors.append(forms.ValidationError(ugettext_lazy("Die Domain darf maximal 255 Zeichen lang sein")))
#             if not check.has_only_allowed_chars():
#                 errors.append(forms.ValidationError(ugettext_lazy("Die Domain darf lediglich Buchstaben, Ziffern, Punkte und Minusse enthalten")))
#             if not errors:
#                 errors.append(forms.ValidationError(ugettext_lazy("Die Domain ist nicht gültig")))
# 
#             raise forms.ValidationError(errors)
# 
#         return check.get_match()  #dyndomain
# 
# Path: upribox_interface/vpn/models.py
# class VpnProfile(models.Model):
#     profilename = models.CharField(max_length=32)
#     config = models.TextField()
#     creation_date = models.DateField(auto_now_add=True)
#     # first slug - this field is used to reference the object, e.g. when creating a download link or when deleting
#     slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id)
#     # second slug - this field is used for the download link
#     download_slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id, always_update=True, null=True)
#     download_valid_until = models.DateTimeField(null=True)
#     dyndomain = models.CharField(max_length=256)
# 
#     class Meta:
#         ordering = ["creation_date"]


import logging
import time
import requests
import lib.utils as utils
from datetime import timedelta
from os.path import exists
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import render
from django.utils import timezone
from django.utils.translation import ugettext as _
from django.views.decorators.http import (require_GET, require_http_methods,
                                          require_POST)
from lib import jobs
from . import jobs as vpnjobs
from .forms import VpnProfileForm
from .models import VpnProfile
    # Get log lines with TLS-auth error after connection
    try:
        with open(settings.OPENVPN_LOGFILE) as f:
            log_lines_after = f.readlines()
    except IOError:
        return HttpResponse('{{"status": "error", "msg": "{}"}}'.format(_("openvpn.log konnte nicht geöffnet werden.")))

    # Count error messages in logs
    count_errors_before = 0
    for ll in log_lines_before:
        if ll.find("TLS Error") and ll.find(r.text):
            count_errors_before += 1

    count_errors_after = 0
    for ll in log_lines_after:
        if ll.find("TLS Error") and ll.find(r.text):
            count_errors_after += 1

    # Check if error messages occurred
    if count_errors_before < count_errors_after:
        # Connection succeeded
        return HttpResponse('{{"status": "success", "msg": "{}"}}'.format(_("Die Verbindung war erfolgreich!")))
    else:
        # Connection failed
        return HttpResponse('{{"status": "failure", "msg": "{}"}}'.format(_("Die Verbindung war nicht erfolgreich!")))


@require_GET
@login_required
def vpn_config(request):

# Path: upribox_interface/vpn/forms.py
# class VpnProfileForm(forms.Form):
# 
#     profilename = forms.CharField(
#         required=True,
#         label=ugettext_lazy("Name:"),
#         max_length=64,
#     )
# 
#     dyndomain = forms.CharField(
#         required=True,
#         label=ugettext_lazy("Domain:"),
#         max_length=64,
#     )
# 
#     def __init__(self, *args, **kwargs):
#         super(VpnProfileForm, self).__init__(*args, **kwargs)
# 
#         upri_dns_domain = None
# 
#         try:
#             upri_dns_domain = get_fact('dns', 'dns', 'hostname')
#         except:
#             logger.error('Kein upri DNS fact gefunden.')
# 
#         if upri_dns_domain:
#             self.fields['dyndomain'].widget = forms.HiddenInput()
#             self.fields['dyndomain'].initial = upri_dns_domain
#             self.fields['dyndomain'].label = ""
# 
#     def clean_profilename(self):
#         profilename = self.cleaned_data['profilename']
#         try:
#             VpnProfile.objects.get(profilename=profilename)
#             raise forms.ValidationError(ugettext_lazy("Profil existiert bereits"))
#         except VpnProfile.DoesNotExist:
#             return profilename
# 
#     def clean_dyndomain(self):
# 
#         dyndomain = self.cleaned_data['dyndomain']
# 
#         errors = []
#         check = domain.Domain(dyndomain)
# 
#         if not check.is_valid():
#             if not check.has_allowed_length():
#                 errors.append(forms.ValidationError(ugettext_lazy("Die Domain darf maximal 255 Zeichen lang sein")))
#             if not check.has_only_allowed_chars():
#                 errors.append(forms.ValidationError(ugettext_lazy("Die Domain darf lediglich Buchstaben, Ziffern, Punkte und Minusse enthalten")))
#             if not errors:
#                 errors.append(forms.ValidationError(ugettext_lazy("Die Domain ist nicht gültig")))
# 
#             raise forms.ValidationError(errors)
# 
#         return check.get_match()  #dyndomain
# 
# Path: upribox_interface/vpn/models.py
# class VpnProfile(models.Model):
#     profilename = models.CharField(max_length=32)
#     config = models.TextField()
#     creation_date = models.DateField(auto_now_add=True)
#     # first slug - this field is used to reference the object, e.g. when creating a download link or when deleting
#     slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id)
#     # second slug - this field is used for the download link
#     download_slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id, always_update=True, null=True)
#     download_valid_until = models.DateTimeField(null=True)
#     dyndomain = models.CharField(max_length=256)
# 
#     class Meta:
#         ordering = ["creation_date"]


# Path: upribox_interface/vpn/views.py
import logging
import time
import requests
import lib.utils as utils
from datetime import timedelta
from os.path import exists
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import render
from django.utils import timezone
from django.utils.translation import ugettext as _
from django.views.decorators.http import (require_GET, require_http_methods,
                                          require_POST)
from lib import jobs
from . import jobs as vpnjobs
from .forms import VpnProfileForm
from .models import VpnProfile

    # Get log lines with TLS-auth error after connection
    try:
        with open(settings.OPENVPN_LOGFILE) as f:
            log_lines_after = f.readlines()
    except IOError:
        return HttpResponse('{{"status": "error", "msg": "{}"}}'.format(_("openvpn.log konnte nicht geöffnet werden.")))

    # Count error messages in logs
    count_errors_before = 0
    for ll in log_lines_before:
        if ll.find("TLS Error") and ll.find(r.text):
            count_errors_before += 1

    count_errors_after = 0
    for ll in log_lines_after:
        if ll.find("TLS Error") and ll.find(r.text):
            count_errors_after += 1

    # Check if error messages occurred
    if count_errors_before < count_errors_after:
        # Connection succeeded
        return HttpResponse('{{"status": "success", "msg": "{}"}}'.format(_("Die Verbindung war erfolgreich!")))
    else:
        # Connection failed
        return HttpResponse('{{"status": "failure", "msg": "{}"}}'.format(_("Die Verbindung war nicht erfolgreich!")))


@require_GET
@login_required
def vpn_config(request):

    context = {'messagestore': jobs.get_messages(), 'profiles': VpnProfile.objects.all(), 'form': VpnProfileForm()}