def samba_server_settings(request):

    return_dict = {}
    #print 'a1'
    try:
        try:
            #print 'a'
            d = samba_settings.load_auth_settings()
            #print 'b'
        except Exception, e:
            return_dict[
                "error"] = "Error loading authentication configuration - %s" % e
            return django.shortcuts.render_to_response(
                'logged_in_error.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))

        if "action" in request.REQUEST and request.REQUEST["action"] == "edit":
            ini = {}
            if d:
                for k in d.keys():
                    ini[k] = d[k]
            if d and d["security"] == "ads":
                form = samba_shares_forms.AuthADSettingsForm(initial=ini)
            #elif d["security"] == "users":
            else:
                #print 'c'
                form = samba_shares_forms.AuthUsersSettingsForm(initial=ini)
                #print 'd'
            return_dict["form"] = form
            return django.shortcuts.render_to_response(
                'edit_samba_server_settings.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))

        # Else a view request
        return_dict["samba_global_dict"] = d
        #print 'a2'

        if "action" in request.REQUEST and request.REQUEST["action"] == "saved":
            return_dict["conf"] = "Information updated successfully"
        return django.shortcuts.render_to_response(
            'view_samba_server_settings.html',
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def samba_server_settings(request):

  return_dict = {}
  #print 'a1'
  try:
    d, err = cifs_common.load_auth_settings()
    if err:
      raise Exception(err)
  
    if "action" in request.REQUEST and request.REQUEST["action"] == "edit":
      ini = {}
      if d:    
        for k in d.keys():
          if d[k]:
            ini[k] = d[k] 
      if d and d["security"] == "ads":
        form = samba_shares_forms.AuthADSettingsForm(initial=ini)
      #elif d["security"] == "users":
      else:
        #print 'c'
        form = samba_shares_forms.AuthUsersSettingsForm(initial=ini)
        #print 'd'
      return_dict["form"] = form
      return django.shortcuts.render_to_response('edit_samba_server_settings.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
    # Else a view request
    return_dict["samba_global_dict"] = d
    #print 'a2'
  
    if "ack" in request.REQUEST and request.REQUEST["ack"] == "saved":
      return_dict["ack_message"] = "Information updated successfully"
    return django.shortcuts.render_to_response('view_samba_server_settings.html', return_dict, context_instance=django.template.context.RequestContext(request))
  except Exception, e:
    return_dict['base_template'] = "services_base.html"
    return_dict["page_title"] = 'Modify CIFS authentication settings'
    return_dict['tab'] = 'auth_server_settings_tab'
    return_dict["error"] = 'Error modifying CIFS authentication settings'
    return_dict["error_details"] = str(e)
    return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
def save_samba_server_settings(request):

  return_dict = {}
  try:
    if request.method != "POST":
      raise Exception("Invalid access method. Please try again using the menus")
  
    if "security" not in request.POST:
      raise Exception("Invalid security specification. Please try again using the menus")
  
    if request.POST["security"] == "ads":
      form = samba_shares_forms.AuthADSettingsForm(request.POST)
    elif request.POST["security"] == "users":
      form = samba_shares_forms.AuthUsersSettingsForm(request.POST)
    else:
      raise Exception("Invalid security specification. Please try again using the menus")
  
    return_dict["form"] = form
    return_dict["ack"] = "edit"
  
    if form.is_valid():
      cd = form.cleaned_data
      print "Calling auth save settings" 
      ret, err = cifs_common.save_auth_settings(cd)
      print "save settings done"
      if err:
        raise Exception(err)
      if cd["security"] == "ads":
        ret, err = cifs_common.generate_krb5_conf()
        if err:
          raise Exception(err)
      ret, err = cifs_unicell.generate_smb_conf()
      if err:
        raise Exception(err)
      #ret, err = local_users.create_local_user('integralstor_guest', 'IntegralStor_Guest_User', 'integralstorguest')
      # Monkey patch to say skip if user exists. Fix it in integralstor_unicell.cifs
      #if 'The user "integralstor_guest" already exists' in err:
      #  pass
      if cd["security"] == "ads":
        rc, err = cifs_unicell.kinit("administrator", cd["password"], cd["realm"])
        if err:
          raise Exception(err)
        rc, err = cifs_unicell.net_ads_join("administrator", cd["password"], cd["password_server"])
        if err:
          raise Exception(err)
      ret, err = cifs_unicell.reload_configuration()
      if err:
        raise Exception(err)
      #print '6'
    else:
      return django.shortcuts.render_to_response('edit_samba_server_settings.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
    #print '7'
    audit_str = "Modified share authentication settings"
    audit.audit("modify_samba_settings", audit_str, request.META)
    return_dict["form"] = form
    return_dict["ack_message"] = "Information successfully updated"
    #print '8'
    return django.http.HttpResponseRedirect('/auth_server_settings?ack=saved')
    #return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))
  except Exception, e:
    return_dict['base_template'] = "services_base.html"
    return_dict["page_title"] = 'Modify CIFS authentication settings'
    return_dict['tab'] = 'auth_server_settings_tab'
    return_dict["error"] = 'Error modifying CIFS authentication settings'
    return_dict["error_details"] = str(e)
    return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
def save_samba_server_settings(request):

    return_dict = {}
    try:
        if request.method != "POST":
            return_dict[
                "error"] = "Invalid access method. Please try again using the menus"
            return django.shortcuts.render_to_response(
                'logged_in_error.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))

        if "security" not in request.POST:
            return_dict[
                "error"] = "Invalid security specification. Please try again using the menus"
            return django.shortcuts.render_to_response(
                'logged_in_error.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))

        if request.POST["security"] == "ads":
            form = samba_shares_forms.AuthADSettingsForm(request.POST)
        elif request.POST["security"] == "users":
            form = samba_shares_forms.AuthUsersSettingsForm(request.POST)
        else:
            return_dict[
                "error"] = "Invalid security specification. Please try again using the menus"
            return django.shortcuts.render_to_response(
                'logged_in_error.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))

        return_dict["form"] = form
        return_dict["action"] = "edit"

        if form.is_valid():
            cd = form.cleaned_data

            try:
                samba_settings.save_auth_settings(cd)
                #print '1'

                ipinfo = networking.get_ip_info('bond0')
                if cd["security"] == "ads":
                    # We now need to add the AD server as the forwarder in our DNS config on the primary...
                    nsl = networking.get_name_servers()
                    if not nsl:
                        raise Exception(
                            "Could not detect the IP addresses of the primary and secondary GRIDCells"
                        )
                    rc = networking.generate_default_primary_named_conf(
                        nsl[0], ipinfo['netmask'], nsl[1], True,
                        cd['password_server_ip'], False)
                    if rc != 0:
                        raise Exception(
                            "Error updating the DNS configuration on the primary GRIDCell"
                        )

                    # ... and on the secondary
                    client = salt.client.LocalClient()
                    r2 = client.cmd(
                        'roles:secondary',
                        'cmd.run_all', [
                            'python /opt/fractalio/scripts/python/create_secondary_named_config.py %s %s %s %s'
                            % (nsl[0], nsl[1], ipinfo['netmask'],
                               cd['password_server_ip'])
                        ],
                        expr_form='grain')
                    if r2:
                        for node, ret in r2.items():
                            if ret["retcode"] != 0:
                                raise Exception(
                                    "Error updating the DNS configuration on the primary GRIDCell"
                                )

                #print '2'
            except Exception, e:
                return_dict[
                    "error"] = "Error saving authentication settings - %s" % e
            if not "error" in return_dict and cd["security"] == "ads":
                try:
                    samba_settings.generate_krb5_conf()
                    #print '3'
                except Exception, e:
                    return_dict[
                        "error"] = "Error generating kerberos config file - %s" % e
            if not "error" in return_dict:
                try:
                    samba_settings.generate_smb_conf()
                    #print '4'
                except Exception, e:
                    return_dict[
                        "error"] = "Error generating file share authentication config file- %s" % e
def update_samba_server_settings(request):

    return_dict = {}
    try:
        if request.method == "GET":
            d, err = cifs_common.get_auth_settings()
            if err:
                raise Exception(err)
            ini = {}
            if d:
                for k in d.keys():
                    if d[k]:
                        ini[k] = d[k]
            else:
                ini['security'] = 'users'
            if d and d["security"] == "ads":
                form = samba_shares_forms.AuthADSettingsForm(initial=ini)
            else:
                form = samba_shares_forms.AuthUsersSettingsForm(initial=ini)
            print 'c'
            return_dict["form"] = form
            return django.shortcuts.render_to_response(
                'update_samba_server_settings.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            if "security" not in request.POST:
                raise Exception(
                    "Invalid security specification. Please try again using the menus"
                )

            if request.POST["security"] == "ads":
                form = samba_shares_forms.AuthADSettingsForm(request.POST)
            elif request.POST["security"] == "users":
                form = samba_shares_forms.AuthUsersSettingsForm(request.POST)
            else:
                raise Exception(
                    "Invalid security specification. Please try again using the menus"
                )

            return_dict["form"] = form
            return_dict["ack"] = "edit"

            if form.is_valid():
                cd = form.cleaned_data
                # print "Calling auth save settings"
                ret, err = cifs_common.update_auth_settings(cd)
                print "save settings done"
                if err:
                    raise Exception(err)
                if cd["security"] == "ads":
                    ret, err = cifs_common.generate_krb5_conf()
                    if err:
                        raise Exception(err)
                ret, err = cifs_integralstor.generate_smb_conf()
                if err:
                    raise Exception(err)
                if cd["security"] == "ads":
                    rc, err = cifs_integralstor.kinit("administrator",
                                                      cd["password"],
                                                      cd["realm"])
                    if err:
                        raise Exception(err)
                    rc, err = cifs_integralstor.net_ads_join(
                        "administrator", cd["password"], cd["password_server"])
                    if err:
                        raise Exception(err)
                ret, err = cifs_integralstor.reload_configuration()
                if err:
                    raise Exception(err)
            else:
                return django.shortcuts.render_to_response(
                    'update_samba_server_settings.html',
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))

            audit_str = "Modified share authentication settings"
            audit.audit("modify_samba_settings", audit_str, request)
            return django.http.HttpResponseRedirect(
                '/view_samba_server_settings?ack=saved')
        # return django.shortcuts.render_to_response('logged_in_error.html',
        # return_dict,
        # context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "services_base.html"
        return_dict["page_title"] = 'Modify CIFS authentication settings'
        return_dict['tab'] = 'auth_server_settings_tab'
        return_dict["error"] = 'Error modifying CIFS authentication settings'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))