#! /usr/bin/env -S lr -v -l utils

# Find the path to this script
path <- Sys.getenv("LITTLER_SCRIPT_PATH")
validPath <- (length(path) == 1 && file.exists(path))

# Read or guess TRACTOR_HOME
homePath <- Sys.getenv("TRACTOR_HOME")
if (homePath == "") {
    if (validPath) {
        homePath <- normalizePath(file.path(dirname(path), ".."))
        warning("TRACTOR_HOME is not set: it will be guessed as ", homePath, immediate.=TRUE)
    } else {
        stop("TRACTOR_HOME is not set and cannot be guessed")
    }
}

tractorVersion <- readLines(file.path(homePath, "VERSION"))

# Set the library path and load packages
.libPaths(c(file.path(homePath, "lib", "R")))

library(arrg)
library(tractor.utils)
library(tractor.session)

if (Sys.getenv("COLUMNS") != "")
    options(width=as.integer(Sys.getenv("COLUMNS")))

defaultWorkingDirectory <- "."
if (Sys.getenv("TRACTOR_WORKING_DIR") != "")
    defaultWorkingDirectory <- Sys.getenv("TRACTOR_WORKING_DIR")

parser <- arrg("furrow",
            opt("h,help", "Display this usage information and exit"),
            opt("z,nohistory", "Do not write the command line used into a history log file"),
            opt("n,stems", "Do not append a suffix to image filenames, giving the file stem instead"),
            opt("r,relative", "Generate paths relative to the working directory, rather than absolute paths"),
            opt("w,workdir", "Specify the working directory, which will be created if necessary", arg="dir", default=defaultWorkingDirectory),
            patterns=list(pat("command", "arg...?", options="znrw"),
                          pat(options="h!")),
            header=c(ore::es("furrow (program v3.5.0, distribution v#{tractorVersion})"), "Channel a command through TractoR's shorthand"),
            footer="Run the specified command, which can be any standard program or script on the PATH, after first expanding TractoR's image-path shorthand, such as @FA for the fractional anisotropy map in the current session directory, or /data/subject1@diffusion/data for the diffusion data series from the session rooted at /data/subject1.")

args <- parser$parse(argv)
if (isTRUE(args$help)) {
    parser$show()
    quit("no")
}

if (is.null(args$workdir)) {
    args$workdir <- "."
} else if (!file.exists(args$workdir)) {
    dir.create(args$workdir, recursive=TRUE)
}

expandedArgs <- character(0)
if (!is.null(args$arg))
    expandedArgs <- expandArguments(args$arg, args$workdir, !args$stems, args$relative)

# NB: expandArguments() sets the working directory
status <- system2(args$command, expandedArgs)

# We are now in the working directory, so don't preface the log filename with it
if (!isTRUE(args$nohistory)) {
    handle <- file("tractor-history.log", "a")
    writeLines(ore::es("[#{date()}] #{ifelse(validPath,path,'furrow')} #{paste(commandArgs(TRUE),collapse=' ')} [#{status}S]"), handle)
    close(handle)
}

quit("no", status)
