#
# This function attempts to keep track of temp mount points on a Linux
# system.  We depend on /etc/mtab so if that file does not exist, we bail.
# Only mount points that are not mounted at boot time or are on another
# system are found, the assumption being that those mounted at boot time
# and not remote will stick around and  what we really want is to keep
# track of the ones that are temporary.

# proc getTempMounts returns a list of temp mount points sorted in
# decreasing order. This makes testing a given dir go like so:
#
# foreach mp [getTempMounts] {
#    if {[regexp "^${mp}(\$|/.*)" $file] $testdir]} {
#        <found>
#    }
# }
#
# The following two lines are for auto_mkindex ...
proc getTempMounts {} {return {}}
proc isTempMountPt {f} {return 0}

if {$::tcl_platform(platform) == "windows"} {
  proc getTempMounts {} {return {}}
  proc ifTempMountPt {f} {return 0}
} else {
  namespace eval getTempMounts {
    variable fstabList
    variable fstabList
    namespace export 
    set err {}
    set merr {}
    proc newList {} {
      variable fstabList
      # darn, work to do...
      set mountList {}
      # do we have the fstab list?
      if {![info exists fstabList]} {
	if {[catch {set cntrl [split [read [open /etc/fstab r]] \n]}] != 0} {
	  return {}
	}
	set fstabList {}
	foreach ln $cntrl {
	  lassign $ln sys mp fs ops
	  if {$sys == {} || [string range $sys 0 0] == "#"} {continue}
	  if {[string match "*noauto*" $ops]} {continue}
	  if {$fs in {cifs nfs smbfs ncpfs fuse.sshfs}} {continue}
	  lappend fstabList $mp
	}
      }
      #puts "fstab: $fstabList"
      # we always read mtab as there is no way to detect changes otherwise.
      set mountList {}
      if {[catch {set cntrl [split [read [open /etc/mtab r]] \n]}] != 0} {
	return {}
      }
      foreach ln $cntrl {
	lassign $ln sys mp dm ops
	if {$sys == {} || [string index $sys 0] == "#"} {continue}
	if {$dm in "$sys nfsd rpc_pipefs" ||
	    [string match "/proc/*" $mp] ||
	    $mp in $fstabList } {continue}
	#puts "yes: $sys $dm $mp"
	lappend mountList $mp
      }
      return [lsort -decreasing -unique $mountList]
    }
  }
  #
  proc getActiveMounts {} {
    return [::getTempMounts::newList]
  }
  proc isTempMountPt {file} {
    foreach mp [::getTempMounts::newList] {
      if {[regexp "^${mp}(\$|/.*)" $file]} {return $mp}
    }
    return {}
  }
}
