---
title: 'Dynamic tool'
output: html_document
---

```{r setup, include=FALSE, warning=FALSE, message=FALSE}
knitr::opts_chunk$set(error = TRUE)
```

## User input

```{r, echo=FALSE}
##-------- build script files -----------

# build script file: script.sh
df = read.table(paste0(Sys.getenv('REPORT_FILES_PATH'), '/options_and_arguments.txt'), 
                sep = '|', header = TRUE)

# get tool name
tool_name = df[df$type == 'tool_name', 'value']
# build script for displaying help messages (this probably should be tool specific)
write(paste0(tool_name, ' -h'), 
        file = paste0(Sys.getenv('REPORT_FILES_PATH'), '/help.sh'))

knitr::kable(df[, c('flag', 'value')])

# if the number of option/argument pairs is larger than 0, build script file
df2 = df[df$type != 'tool_name', ]
if (nrow(df2) > 0) {
  # write tool name as the first line of the script.sh
  # before running the job, cd into the ${REPORT_FILES_PATH} directory
  write(paste0(tool_name, ' \\'), 
        paste0(Sys.getenv('REPORT_FILES_PATH'), '/script.sh'))
  df2 = df[df$type != 'tool_name', ]
  write(paste(' ', df2$flag, df2$value, '\\', sep = ' '), 
        file = paste0(Sys.getenv('REPORT_FILES_PATH'), '/script.sh'), 
        append = TRUE )
  # remember that after writing option/argument lines to the script.sh, the last line
  # has an extra newline character '\' which causes a problem. We can either remove that extra
  # '\' or add a new line to the end. We choose to add a new line.
  
  # add an extra line to the end to redirect stdout to stdout.txt and stderr to stderr.txt
  write('  > ${REPORT_FILES_PATH}/stdout.txt 2>${REPORT_FILES_PATH}/stderr.txt', 
        paste0(Sys.getenv('REPORT_FILES_PATH'), '/script.sh'), append = TRUE)
} else {
  # if no option/argument input, simply display the help message
  write(paste0(tool_name, ' -h'), 
        file = paste0(Sys.getenv('REPORT_FILES_PATH'), '/script.sh'))
}

```


```{bash, echo=FALSE}
## code to open help documentation
sh ${REPORT_FILES_PATH}/help.sh > ${TOOL_HELP_DOC}
```

```{bash, results='asis', echo=FALSE}
echo '## Show help documentation'
echo ''
echo ''
echo '```bash'
cat ${REPORT_FILES_PATH}/help.sh
echo '```'
```


```{bash, echo=FALSE}
# run job script
# it's important to run the job within the REPORT_FILES_PATH
cd ${REPORT_FILES_PATH} && sh script.sh
```

```{bash, results='asis', echo=FALSE}
echo '## Job script'
echo ''
echo ''
echo '```bash'
cat ${REPORT_FILES_PATH}/script.sh
echo '```'
```


```{r, results='asis', echo=FALSE}
cat('##All output files')
cat('\n\n')
all_files = list.files(path = Sys.getenv('REPORT_FILES_PATH'), 
                       full.names = TRUE, 
                       recursive = TRUE)

for (f in sub(Sys.getenv('REPORT_FILES_PATH'), '.', all_files) ) {
  cat('* [', f, '](', f, ')\n')
}
cat('\n')
```

