def delete_share(request):
  
  return_dict = {}
  try:
    if request.method == "GET":
      #Return the conf page
      share_id = request.GET["share_id"]
      name = request.GET["name"]
      return_dict["share_id"] = share_id
      return_dict["name"] = name
      return django.shortcuts.render_to_response("delete_share_conf.html", return_dict, context_instance = django.template.context.RequestContext(request))
    else:
      share_id = request.POST["share_id"]
      name = request.POST["name"]
      #logger.debug("Delete share request for name %s"%name)
      try :
        samba_settings.delete_share(share_id)
        samba_settings.generate_smb_conf()
      except Exception, e:
        return_dict["error"] = "Error deleting share - %s" %e
        return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
      audit_str = "Deleted Samba share %s"%name
      audit.audit("delete_share", audit_str, request.META["REMOTE_ADDR"])
      return django.http.HttpResponseRedirect('/display_shares?action=deleted')
  except Exception, e:
    s = str(e)
    if "Another transaction is in progress".lower() in s.lower():
      return_dict["error"] = "An underlying storage operation has locked a volume so we are unable to process this request. Please try after a couple of seconds"
    else:
      return_dict["error"] = "An error occurred when processing your request : %s"%s
    return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
def edit_auth_method(request):
  return_dict = {}
  try:
    try :
      d = samba_settings.load_auth_settings()
    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))
    return_dict["samba_global_dict"] = d
  
    if request.method == "GET":
      return django.shortcuts.render_to_response('edit_auth_method.html', return_dict, context_instance=django.template.context.RequestContext(request))
    else:
      #Save request
      if "auth_method" not in request.POST:
        return_dict["error"] = "Please select an authentication method" 
        return django.shortcuts.render_to_response('edit_auth_method.html', return_dict, context_instance=django.template.context.RequestContext(request))
      security = request.POST["auth_method"]
      if security == d["security"]:
        return_dict["error"] = "Selected authentication method is the same as before." 
        return django.shortcuts.render_to_response('edit_auth_method.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
      try:
        samba_settings.change_auth_method(security)
        samba_settings.generate_smb_conf()
      except Exception, e:
        return_dict["error"] = "Error updating authentication method - %s" %e
        return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))
def edit_auth_method(request):
    return_dict = {}
    try:
        try:
            d = samba_settings.load_auth_settings()
        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))
        return_dict["samba_global_dict"] = d

        if request.method == "GET":
            return django.shortcuts.render_to_response(
                'edit_auth_method.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            #Save request
            if "auth_method" not in request.POST:
                return_dict["error"] = "Please select an authentication method"
                return django.shortcuts.render_to_response(
                    'edit_auth_method.html',
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
            security = request.POST["auth_method"]
            if security == d["security"]:
                return_dict[
                    "error"] = "Selected authentication method is the same as before."
                return django.shortcuts.render_to_response(
                    'edit_auth_method.html',
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))

            try:
                samba_settings.change_auth_method(security)
                samba_settings.generate_smb_conf()
            except Exception, e:
                return_dict[
                    "error"] = "Error updating authentication method - %s" % 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'
            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 delete_share(request):

    return_dict = {}
    try:
        if request.method == "GET":
            #Return the conf page
            share_id = request.GET["share_id"]
            name = request.GET["name"]
            return_dict["share_id"] = share_id
            return_dict["name"] = name
            return django.shortcuts.render_to_response(
                "delete_share_conf.html",
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            share_id = request.POST["share_id"]
            name = request.POST["name"]
            #logger.debug("Delete share request for name %s"%name)
            try:
                samba_settings.delete_share(share_id)
                samba_settings.generate_smb_conf()
            except Exception, e:
                return_dict["error"] = "Error deleting share - %s" % e
                return django.shortcuts.render_to_response(
                    'logged_in_error.html',
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))

            audit_str = "Deleted Samba share %s" % name
            audit.audit("delete_share", audit_str, request.META["REMOTE_ADDR"])
            return django.http.HttpResponseRedirect(
                '/display_shares?action=deleted')
    except Exception, e:
        s = str(e)
        if "Another transaction is in progress".lower() in s.lower():
            return_dict[
                "error"] = "An underlying storage operation has locked a volume so we are unable to process this request. Please try after a couple of seconds"
        else:
            return_dict[
                "error"] = "An error occurred when processing your request : %s" % s
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def delete_share(request):

    return_dict = {}
    try:
        if request.method == "GET":
            # Return the conf page
            share_id = request.GET["share_id"]
            name = request.GET["name"]
            return_dict["share_id"] = share_id
            return_dict["name"] = name
            return django.shortcuts.render_to_response(
                "delete_share_conf.html", return_dict, context_instance=django.template.context.RequestContext(request)
            )
        else:
            share_id = request.POST["share_id"]
            name = request.POST["name"]
            # logger.debug("Delete share request for name %s"%name)
            try:
                samba_settings.delete_share(share_id)
                samba_settings.generate_smb_conf()
            except Exception, e:
                return_dict["error"] = "Error deleting share - %s" % e
                return django.shortcuts.render_to_response(
                    "logged_in_error.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(request),
                )

            audit_str = "Deleted CIFS share %s" % name
            audit.audit("delete_share", audit_str, request.META["REMOTE_ADDR"])
            return django.http.HttpResponseRedirect("/display_shares?action=deleted")
    except Exception, e:
        s = str(e)
        return_dict["error"] = "An error occurred when processing your request : %s" % s
        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 create_share(request):

  return_dict = {}
  try:
    user_list = samba_settings.get_user_list()
    group_list = samba_settings.get_group_list()
  
    if request.method == "GET":
      #Return the form
      form = samba_shares_forms.ShareForm(user_list = user_list, group_list = group_list)
      return_dict["form"] = form
      return django.shortcuts.render_to_response("create_share.html", return_dict, context_instance = django.template.context.RequestContext(request))
    else:
      #Form submission so create
      return_dict = {}
      form = samba_shares_forms.ShareForm(request.POST, user_list = user_list, group_list = group_list)
      return_dict["form"] = form
      if form.is_valid():
        cd = form.cleaned_data
        name = cd["name"]
        path = "%s"%cd["path"]
        if not path:
          return_dict["path_error"] = "Please choose a path."
          return django.shortcuts.render_to_response("create_share.html", return_dict, context_instance = django.template.context.RequestContext(request))
        
        if "comment" in cd:
          comment = cd["comment"]
        else:
          comment = None
        if "read_only" in cd:
          read_only = cd["read_only"]
        else:
          read_only = None
        if "browseable" in cd:
          browseable = cd["browseable"]
        else:
          browseable = None
        if "guest_ok" in cd:
          guest_ok = cd["guest_ok"]
        else:
          guest_ok = None
        if "users" in cd:
          users = cd["users"]
        else:
          users = None
        if "groups" in cd:
          groups = cd["groups"]
        else:
          groups = None
        vol = cd["vol"]
        #logger.debug("Create share request, name %s path %s, comment %s, read_only %s, browseable %s, guest_ok %s, users %s, groups %s, vol %s"%(name, path, comment, read_only, browseable, guest_ok, users, groups))
        try :
          samba_settings.create_share(name, comment, guest_ok, read_only, path, display_path, browseable, users, groups)
          samba_settings.generate_smb_conf()
        except Exception, e:
          return_dict["error"] = "Error creating share - %s" %e
          return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
        audit_str = "Created Samba share %s"%name
        audit.audit("create_share", audit_str, request.META["REMOTE_ADDR"])
        return django.http.HttpResponseRedirect('/display_shares?action=created')
      else:
           browseable = False
         if "guest_ok" in cd:
           guest_ok = cd["guest_ok"]
         else:
           guest_ok = False
         if "users" in cd:
           users = cd["users"]
         else:
           users = None
         if "groups" in cd:
           groups = cd["groups"]
         else:
           groups = None
         #logger.debug("Save share request, name %s path %s, comment %s, read_only %s, browseable %s, guest_ok %s, users %s, groups %s, vol %s"%(name, path, comment, read_only, browseable, guest_ok, users, groups))
         samba_settings.save_share(share_id, name, comment, guest_ok, read_only, path, browseable, users, groups)
         samba_settings.generate_smb_conf()
       except Exception, e:
         return_dict["error"] = "Error saving share information - %s" %e
         return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))
 
       audit_str = "Modified share %s"%cd["name"]
       audit.audit("modify_share", audit_str, request.META["REMOTE_ADDR"])
 
       return django.http.HttpResponseRedirect('/view_share?access_mode=by_id&index=%s&action=saved'%cd["share_id"])
 
     else:
       #Invalid form
       return django.shortcuts.render_to_response('edit_share.html', return_dict, context_instance=django.template.context.RequestContext(request))
 except Exception, e:
   s = str(e)
   return_dict["error"] = "An error occurred when processing your request : %s"%s
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 create_share(request):

    return_dict = {}
    try:
        user_list = samba_settings.get_user_list()
        group_list = samba_settings.get_group_list()

        if request.method == "GET":
            #Return the form
            form = samba_shares_forms.ShareForm(user_list=user_list,
                                                group_list=group_list)
            return_dict["form"] = form
            return django.shortcuts.render_to_response(
                "create_share.html",
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            #Form submission so create
            return_dict = {}
            form = samba_shares_forms.ShareForm(request.POST,
                                                user_list=user_list,
                                                group_list=group_list)
            return_dict["form"] = form
            if form.is_valid():
                cd = form.cleaned_data
                name = cd["name"]
                path = "%s" % cd["path"]
                if not path:
                    return_dict["path_error"] = "Please choose a path."
                    return django.shortcuts.render_to_response(
                        "create_share.html",
                        return_dict,
                        context_instance=django.template.context.
                        RequestContext(request))

                if "comment" in cd:
                    comment = cd["comment"]
                else:
                    comment = None
                if "read_only" in cd:
                    read_only = cd["read_only"]
                else:
                    read_only = None
                if "browseable" in cd:
                    browseable = cd["browseable"]
                else:
                    browseable = None
                if "guest_ok" in cd:
                    guest_ok = cd["guest_ok"]
                else:
                    guest_ok = None
                if "users" in cd:
                    users = cd["users"]
                else:
                    users = None
                if "groups" in cd:
                    groups = cd["groups"]
                else:
                    groups = None
                vol = cd["vol"]
                #logger.debug("Create share request, name %s path %s, comment %s, read_only %s, browseable %s, guest_ok %s, users %s, groups %s, vol %s"%(name, path, comment, read_only, browseable, guest_ok, users, groups))
                try:
                    samba_settings.create_share(name, comment, guest_ok,
                                                read_only, path, display_path,
                                                browseable, users, groups)
                    samba_settings.generate_smb_conf()
                except Exception, e:
                    return_dict["error"] = "Error creating share - %s" % e
                    return django.shortcuts.render_to_response(
                        'logged_in_error.html',
                        return_dict,
                        context_instance=django.template.context.
                        RequestContext(request))

                audit_str = "Created Samba share %s" % name
                audit.audit("create_share", audit_str,
                            request.META["REMOTE_ADDR"])
                return django.http.HttpResponseRedirect(
                    '/display_shares?action=created')
            else:
                        guest_ok = cd["guest_ok"]
                    else:
                        guest_ok = False
                    if "users" in cd:
                        users = cd["users"]
                    else:
                        users = None
                    if "groups" in cd:
                        groups = cd["groups"]
                    else:
                        groups = None
                    #logger.debug("Save share request, name %s path %s, comment %s, read_only %s, browseable %s, guest_ok %s, users %s, groups %s, vol %s"%(name, path, comment, read_only, browseable, guest_ok, users, groups))
                    samba_settings.save_share(share_id, name, comment,
                                              guest_ok, read_only, path,
                                              browseable, users, groups)
                    samba_settings.generate_smb_conf()
                except Exception, e:
                    return_dict[
                        "error"] = "Error saving share information - %s" % e
                    return django.shortcuts.render_to_response(
                        'logged_in_error.html',
                        return_dict,
                        context_instance=django.template.context.
                        RequestContext(request))

                audit_str = "Modified share %s" % cd["name"]
                audit.audit("modify_share", audit_str,
                            request.META["REMOTE_ADDR"])

                return django.http.HttpResponseRedirect(
                    '/view_share?access_mode=by_id&index=%s&action=saved' %