## rsync_and_copy_utils.r

## This file was created on 2015-08-19
##
##  Other functions of the BringMe ... variety should perhaps go here too.
##  We can move the orchard specific parts to Options

make_rsync_to_copy_files <- function(from, to, add_trailing_slash=TRUE, remove_source_after_copy=FALSE, ignore_existing=TRUE, check_exists=TRUE, verbose_rsync=TRUE, verbose=TRUE) {
## FORMAT:
##    rsync -a -v --ignore-existing <src> <dst>

  ## NOTE TO SELF:  If destination does not exist, rsync will actually create it. 
  if (check_exists) {
    stopifnot(file.exists(from) || (grepl("(\\*|\\.)$", from) && file.exists(dirname(from))))
    stopifnot(file.exists(to))
  }

  if (add_trailing_slash) {
      has_slash <- . %>% grepl("/(\\.?\\*?)$", .)

      if (isdir(from)) {
        if (!has_slash(from))
        from %<>% paste0("/")
      }

      if (isdir(to)) {
        if (!has_slash(to))
          to %<>% paste0("/")
      }
  }

  # ret <- sprintf("rsync -a -v --ignore-existing %s %s", shellClean(from), shellClean(to))

  cmd <- "rsync -a"
  if (verbose_rsync)
    cmd %<>% paste("-v")
  if (ignore_existing)
    cmd %<>% paste("--ignore-existing")
  if (remove_source_after_copy)
    cmd %<>% paste("--remove-source-files")

  cmd <- paste(cmd, shellClean(from, warnAsterisk=TRUE), shellClean(to, warnAsterisk=TRUE), sep=" ")
  if (verbose)
    catn(cmd)

  return(invisible(cmd))
}