#
# <20170120.1527.22>
#
# This is a bit of code to do the "cp -pfrl" command using file mkdir and file link
#
# args are options such as cp has.
# -L is the only one we check for.
# if -L is present, we hard link to files pointed to by softlinks
# if -L is NOT present, we ignore symbolic links
#
proc recHardLink {source dest args} {
  if {! [file isdirectory $source]} {
    if {[file exists $source]} {
      if {[file isdirectory $dest]} {
	set dest $dest/[file tail $source]
      }
      file link -hard  $dest $source
    }
    return
  }
  # that was the easy stuff...
  if {![file isdirectory $dest]} {
    error "Recursive Hard Link: Destination ($dest) not a directory"
  }
  set op [expr {"-L" in $args}]
  recHardLinkRecur $source $dest $op
  # steps 1: create destion dir
  # step  2: link all files in source to new dest
  # do the same for each dir in source, recursively
}
# op is true if we are to handle links...
proc recHardLinkRecur {sor dest op} {
  set tail [file tail $sor]
  file mkdir $dest/$tail
  if {$::tcl_platform(platform) == "unix"} {
    set flist [glob -nocomplain -path $sor -tails .*]
  } else {
    set flist [glob -nocomplain -directory $sor -tails -type {hidden} *]
  }
  set flist [concat [glob -nocomplain -directory $sor -tails *] $flist]
  # frputs "recHardLink  " flist sor
  foreach file $flist {
    set nfile [file dirname [file normalize $sor/$file/x]]
    # if the normalized and un-normalized differ we have a link
    if {$nfile != "$sor/$file"} {
      if {$op} {
	set nfile [file dirname $nfile]/$file
      } else {
	continue
      }
    }
    # frputs "recHardLink  " nfile dest tail sor file
    if {[file isdirectory $nfile]} {
      recHardLinkRecur $nfile $dest/$tail $op
    } else {
      file link -hard $dest/$tail/$file $nfile
    }
  }
}
