#
# <20210119.1243.23>
#
# The chmod code
#
proc CmdChmod {} {
  global glob
  CmdChmod_ $glob(listbox,left).file glob(left,filelist) \
      $glob(left,pwd) $glob(right,pwd) left
  CmdChmod_ $glob(listbox,right).file glob(right,filelist) \
      $glob(right,pwd) $glob(left,pwd) right
}

proc CmdChmod_ { listb_name filelist_var frompwd topwd inst } {
  # For speed, (hopefully) we'll call by reference...
  global config glob
  upvar $filelist_var filelist
  set fl {}
  

  foreach sel [$listb_name curselection] {
    if {[CheckAbort [_ "Chmod"]]} return
    set elem [lindex $filelist $sel]
    lassign $elem {*}$glob(fListEl)
    switch $type {
      l   -
      ld  -
      n   -
      d   {
	incr ftpFlag 0
	if {$glob(os) == "WIN32"} {
	  PopInfo [_ "So sorry, can't do chmod on windows files."]
	  return
	}
	set localMode [file attributes $frompwd/$file -permissions]
	lassign [split $usergroup /] user group
      }
      default {
	# Must be an nVFS, maybe we can do it... up to the handler and remote
	incr ftpFlag
	set localMode [GetModeFromString $mode]
	lassign [split $usergroup /] user group
	# puts "got $mode from >[lindex $elem 5]<"
      }
    }
    lappend fl  [DNtoDir [URL join $frompwd $file]]
  }
  # Note to me, we present the flags to the last file in the list
  # but apply the result to all files...
  if {$fl != ""} {
    set rarg [ChmodDialog [DNtoDir [URL join $frompwd $file]] $localMode $user $group]
    lassign $rarg arg ownarg
    if {$arg != ""} {
      if { $ftpFlag } {
	# for ftp we will use a seperate call for each file...
	foreach file $fl {
	  set r [catch {VFSchmod $fl $arg} m ]
	  if { $r != 0 && $r != "" } {
	    PopError [_ "VFS chmod returns: %s" $m]
	    break
	  }
	}
      } else {
	# we need to do this to get the quotes right...
	frECF [list exec {*}[subst {*}$::stOps $config(cmd,chmod)] {*}$arg]\
	    $fl\
	    [list -back $glob(async)]
      }
      ForceUpdate $inst
    }
    if {$ownarg != ""} {
      if { $ftpFlag } {
	# for ftp we will use a seperate call for each file...
	foreach file $fl {
	  set r [catch {VFSchown $fl $ownarg} m]
	  if { $r != "0" && $r != "" } {
	    PopError [_ "VFS chown returns: %s" $m]
	    break
	  }
	}
      } else {
	frECF [list exec {*}[subst {*}$::stOps $config(cmd,chown)] {*}$ownarg]\
	    $fl\
	    [list -back $glob(async)]
	
     }
      ForceUpdate $inst
    }
    
  }
}
