def edit_cifs_share(request):

  return_dict = {}
  try:
    user_list, err = cifs_unicell.get_user_list()
    if err:
      raise Exception(err)
    group_list, err = cifs_unicell.get_group_list()
    if err:
      raise Exception(err)

    if request.method == "GET":
      # Shd be an edit request
      if "share_id" not in request.GET:
        raise Exception("Unknown share specified")

      share_id = request.GET["share_id"]
      share_dict, err = cifs_common.load_share_info("by_id", share_id)
      if err:
        raise Exception(err)
      '''
      valid_users_list, err = cifs_common.load_valid_users_list(share_dict["share_id"])
      if err:
        raise Exception(err)
      '''
  
      # Set initial form values
      initial = {}
      initial["share_id"] = share_dict["share_id"]
      initial["name"] = share_dict["name"]
      initial["path"] = share_dict["path"]
      if share_dict["guest_ok"]:
        initial["guest_ok"] = True
      else:
        initial["guest_ok"] = False
      if share_dict["browseable"]:
        initial["browseable"] = True
      else:
        initial["browseable"] = False
      '''
      if share_dict["read_only"]:
        initial["read_only"] = True
      else:
        initial["read_only"] = False
      '''
      initial["comment"] = share_dict["comment"]
  
      '''
      if valid_users_list:
        vgl = []
        vul = []
        for u in valid_users_list:
          if u["grp"]:
            vgl.append(u["name"])
          else:
            vul.append(u["name"])
        initial["users"] = vul
        initial["groups"] = vgl
      '''
  
      #form = samba_shares_forms.EditShareForm(initial = initial, user_list = user_list, group_list = group_list)
      form = samba_shares_forms.EditShareForm(initial = initial)
  
      return_dict["form"] = form
      return django.shortcuts.render_to_response('edit_cifs_share.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
    else:
  
      # Shd be an save request
      #form = samba_shares_forms.EditShareForm(request.POST, user_list = user_list, group_list = group_list)
      form = samba_shares_forms.EditShareForm(request.POST)
      return_dict["form"] = form
      if form.is_valid():
        cd = form.cleaned_data
        name = cd["name"]
        share_id = cd["share_id"]
        path = cd["path"]
        if "comment" in cd:
          comment = cd["comment"]
        else:
          comment = None
        if "read_only" in cd:
          read_only = cd["read_only"]
        else:
          read_only = False
        if "browseable" in cd:
          browseable = cd["browseable"]
        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))
        ret, err = cifs_common.save_share(share_id, name, comment, False, read_only, path, browseable, None, None)
        if err:
          raise Exception(err)
        ret, err = cifs_unicell.generate_smb_conf()
        if err:
          raise Exception(err)
  
        audit_str = "Modified share %s"%cd["name"]
        audit.audit("modify_cifs_share", audit_str, request.META)
  
        return django.http.HttpResponseRedirect('/view_cifs_share?access_mode=by_id&index=%s&ack=saved'%cd["share_id"])
  
      else:
        #Invalid form
        return django.shortcuts.render_to_response('edit_cifs_share.html', return_dict, context_instance=django.template.context.RequestContext(request))
  except Exception, e:
    return_dict['base_template'] = "shares_base.html"
    return_dict["page_title"] = 'Modify a CIFS share'
    return_dict['tab'] = 'view_cifs_shares_tab'
    return_dict["error"] = 'Error modifying CIFS share'
    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 edit_cifs_share(request):

  return_dict = {}
  try:
    user_list, err = cifs_unicell.get_user_list()
    if err:
      raise Exception(err)
    group_list, err = cifs_unicell.get_group_list()
    if err:
      raise Exception(err)

    if request.method == "GET":
      # Shd be an edit request
      if "share_id" not in request.GET:
        raise Exception("Unknown share specified")

      share_id = request.GET["share_id"]
      share_dict, err = cifs_common.load_share_info("by_id", share_id)
      if err:
        raise Exception(err)
      valid_users_list, err = cifs_common.load_valid_users_list(share_dict["share_id"])
      if err:
        raise Exception(err)
  
      # Set initial form values
      initial = {}
      initial["share_id"] = share_dict["share_id"]
      initial["name"] = share_dict["name"]
      initial["path"] = share_dict["path"]
      if share_dict["guest_ok"]:
        initial["guest_ok"] = True
      else:
        initial["guest_ok"] = False
      if share_dict["browseable"]:
        initial["browseable"] = True
      else:
        initial["browseable"] = False
      if share_dict["read_only"]:
        initial["read_only"] = True
      else:
        initial["read_only"] = False
      initial["comment"] = share_dict["comment"]
  
      if valid_users_list:
        vgl = []
        vul = []
        for u in valid_users_list:
          if u["grp"]:
            vgl.append(u["name"])
          else:
            vul.append(u["name"])
        initial["users"] = vul
        initial["groups"] = vgl
  
      form = samba_shares_forms.EditShareForm(initial = initial, user_list = user_list, group_list = group_list)
  
      return_dict["form"] = form
      return django.shortcuts.render_to_response('edit_cifs_share.html', return_dict, context_instance=django.template.context.RequestContext(request))
  
    else:
  
      # Shd be an save request
      form = samba_shares_forms.EditShareForm(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"]
        share_id = cd["share_id"]
        path = cd["path"]
        if "comment" in cd:
          comment = cd["comment"]
        else:
          comment = None
        if "read_only" in cd:
          read_only = cd["read_only"]
        else:
          read_only = False
        if "browseable" in cd:
          browseable = cd["browseable"]
        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))
        ret, err = cifs_common.save_share(share_id, name, comment, guest_ok, read_only, path, browseable, users, groups)
        if err:
          raise Exception(err)
        ret, err = cifs_unicell.generate_smb_conf()
        if err:
          raise Exception(err)
  
        audit_str = "Modified share %s"%cd["name"]
        audit.audit("modify_cifs_share", audit_str, request.META["REMOTE_ADDR"])
  
        return django.http.HttpResponseRedirect('/view_cifs_share?access_mode=by_id&index=%s&action=saved'%cd["share_id"])
  
      else:
        #Invalid form
        return django.shortcuts.render_to_response('edit_cifs_share.html', return_dict, context_instance=django.template.context.RequestContext(request))
  except Exception, e:
    return_dict['base_template'] = "shares_base.html"
    return_dict["page_title"] = 'Modify a CIFS share'
    return_dict['tab'] = 'view_cifs_shares_tab'
    return_dict["error"] = 'Error modifying CIFS share'
    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 add_aces(request):
  return_dict = {}
  try:
    for_share = False
    if 'for' in request.REQUEST and request.REQUEST['for'] == 'share':
      for_share = True
    if for_share:
      return_dict['base_template'] = "shares_base.html"
      return_dict['tab'] = 'view_cifs_shares_tab'
    else:
      return_dict['base_template'] = "storage_base.html"
      return_dict['tab'] = 'dir_permissions_tab'
      

    if 'path' not in request.REQUEST:
      raise Exception('Invalid request. Please use the menus.')
    path = request.REQUEST["path"]
    return_dict["path"] = path

    aces, err = acl.get_all_aces(path)
    if err:
      raise Exception(err)
    user_list, err = cifs_unicell.get_user_list()
    if err:
      raise Exception(err)
    group_list, err = cifs_unicell.get_group_list()
    if err:
      raise Exception(err)
    new_users, err = acl.get_new_ug_list(aces, user_list, 'user')
    if err:
      raise Exception(err)
    new_groups, err = acl.get_new_ug_list(aces, group_list, 'group')
    if err:
      raise Exception(err)
    return_dict['new_users'] = new_users
    return_dict['new_groups'] = new_groups

    if request.method == "GET":
      initial = {}
      initial['path'] = path
      if for_share:
        if 'share_index' not in request.REQUEST or 'share_name' not in request.REQUEST:
          raise Exception('Invalid request. Please use the menus.')
        share_index = request.REQUEST["share_index"]
        share_name = request.REQUEST["share_name"]
        initial['share_index'] = share_index
        initial['share_name'] = share_name
        form = samba_shares_forms.AddShareAcesForm(initial = initial, user_list = new_users, group_list = new_groups)
      else:
        form = folder_management_forms.AddAcesForm(initial = initial, user_list = new_users, group_list = new_groups)
      return_dict["form"] = form
      if for_share:
        return django.shortcuts.render_to_response("add_cifs_aces.html", return_dict, context_instance = django.template.context.RequestContext(request))
      else:
        return django.shortcuts.render_to_response("add_dir_aces.html", return_dict, context_instance = django.template.context.RequestContext(request))
    else:
      if for_share:
        form = samba_shares_forms.AddShareAcesForm(request.POST, user_list = new_users, group_list = new_groups)
      else:
        form = folder_management_forms.AddAcesForm(request.POST, user_list = new_users, group_list = new_groups)
      return_dict["form"] = form
      if form.is_valid():
        cd = form.cleaned_data
        users = cd['users']
        groups = cd['groups']
        recursive = cd['recursive']
        if for_share:
          share_index = cd['share_index']
          share_name = cd['share_name']
        ret, err = acl.add_ace_entries(path, users, groups, recursive)
        if err:
          raise Exception(err)
      else:
        if for_share:
          return django.shortcuts.render_to_response("add_cifs_aces.html", return_dict, context_instance = django.template.context.RequestContext(request))
        else:
          return django.shortcuts.render_to_response("add_dir_aces.html", return_dict, context_instance = django.template.context.RequestContext(request))
  
      audit_str = 'Added ACL entries : '
      for user in users:
        audit_str += '%s(user) '%user
      for group in groups:
        audit_str += '%s(group) '%group
      if for_share:
        audit_str += ', for CIFS share %s'%share_name
      else:
        audit_str += ', for path %s'%path
      audit.audit("add_aces", audit_str, request.META)
      if for_share:
        return django.http.HttpResponseRedirect('/view_cifs_share?access_mode=by_id&index=%s&ack=aces_added'%share_index)
      else:
        return django.http.HttpResponseRedirect('/view_dir_ownership_permissions?path=%s&ack=aces_added'%path)
  except Exception, e:
    return_dict["page_title"] = 'Add new  ACL entries'
    return_dict["error"] = 'Error adding new ACL entries'
    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 create_cifs_share(request):

  return_dict = {}
  try:
    user_list, err = cifs_unicell.get_user_list()
    if err:
      raise Exception(err)
    group_list, err = cifs_unicell.get_group_list()
    if err:
      raise Exception(err)
    pools, err = zfs.get_pools()
    if err:
      raise Exception('No ZFS pools available. Please create a pool and dataset before creating shares.')

    ds_list = [] 
    for pool in pools:
      for ds in pool["datasets"]:
        if ds['properties']['type']['value'] == 'filesystem':
          ds_list.append({'name': ds["name"], 'mountpoint': ds["mountpoint"]})
    if not ds_list:
      raise Exception('No ZFS datasets available. Please create a dataset before creating shares.')
  
    if request.method == "GET":
      #Return the form

      form = samba_shares_forms.CreateShareForm(user_list = user_list, group_list = group_list, dataset_list = ds_list, initial = {'guest_ok': True})
      return_dict["form"] = form

      return django.shortcuts.render_to_response("create_cifs_share.html", return_dict, context_instance = django.template.context.RequestContext(request))
    else:
      #Form submission so create
      return_dict = {}
      form = samba_shares_forms.CreateShareForm(request.POST, user_list = user_list, group_list = group_list, dataset_list = ds_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_cifs_share.html", return_dict, context_instance = django.template.context.RequestContext(request))
        display_path = cd["path"]    
        if not os.path.isdir(display_path):
          os.mkdir(display_path)
        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 = "unicell"
        #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))
        #print '1'
        ret, err = cifs_common.create_share(name, comment, guest_ok, read_only, display_path, display_path, browseable, users, groups,vol)
        #print '2'
        if err:
          raise Exception(err)
        ret, err = cifs_unicell.generate_smb_conf()
        #print '3'
        if err:
          raise Exception(err)
  
        audit_str = "Created Samba share %s"%name
        audit.audit("create_cifs_share", audit_str, request.META["REMOTE_ADDR"])
        return django.http.HttpResponseRedirect('/view_cifs_shares?action=created')
      else:
        return django.shortcuts.render_to_response("create_cifs_share.html", return_dict, context_instance = django.template.context.RequestContext(request))
  except Exception, e:
    return_dict['base_template'] = "shares_base.html"
    return_dict["page_title"] = 'Create a CIFS share'
    return_dict['tab'] = 'view_cifs_shares_tab'
    return_dict["error"] = 'Error creating a CIFS share'
    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))