#!/usr/bin/env bash

set -e

timestamp=$(date -u)

# Prepare log file
log_file="{{ log_file }}"
if [[ ! -z "$log_file" ]]; then
  log_path="{{ log_path }}"
  log_file="{{ log_path }}/$log_file"
  mkdir -p "$log_path" && touch "$log_file" && echo "Started: $timestamp" >> "$log_file"
  echo --------------------------------------------------------
  echo Log file: "$log_file"
  echo --------------------------------------------------------
else
  log_file="/dev/null"
fi

# Prepare working directory: FreeSurfer does not like it when
# directories contain spaces
wdir_actual="{{ work_path_actual }}"
wdir_fs="{{ work_path_symlink }}"
mri_path="{{ mri_path }}"
input_name="{{ gsub('.*\\.(nii|nii\\.gz)$', 'MRI.\\1', mri_path) }}"
mri_ext="{{ ifelse(grepl('gz$', mri_path, ignore.case = TRUE), '.nii.gz', '.nii') }}"
derivative_path="$wdir_actual/rave-imaging/derivative"
mri_backup="$wdir_actual/rave-imaging/derivative/MRI_RAW$mri_ext"

# Make sure the actual working directory exists
fresh_start={{ ifelse(overwrite, 1, 0) }}
if [[ "$fresh_start" -eq 1 && -d "$wdir_actual/rave-imaging/fs" ]]; then
  rm -r "$wdir_actual/rave-imaging/fs"
fi
mkdir -p "$wdir_actual/rave-imaging/derivative"


# # DEBUG
# log_file="log-recon-all-230618-191153.log"
# if [[ ! -z "$log_file" ]]; then
#   log_path="/Users/dipterix/Dropbox (PennNeurosurgery)/RAVE/Samples/raw/YAH/rave-imaging/log"
#   log_file="/Users/dipterix/Dropbox (PennNeurosurgery)/RAVE/Samples/raw/YAH/rave-imaging/log/$log_file"
#   mkdir -p "$log_path" && touch "$log_file" && echo "Started: $timestamp" >> "$log_file"
#   echo --------------------------------------------------------
#   echo Log file: "$log_file"
#   echo --------------------------------------------------------
# else
#   log_file="/dev/null"
# fi
# wdir_actual="/Users/dipterix/Dropbox (PennNeurosurgery)/RAVE/Samples/raw/YAH"
# wdir_fs="/Users/dipterix/Library/Caches/org.R-project.R/R/ravecore/FreeSurfer/YAH"
# mri_path="/Users/dipterix/Dropbox (PennNeurosurgery)/RAVE/Samples/raw/YAH/rave-imaging/inputs/MRI/MRI_RAW.nii"
# input_name="MRI.nii"
# mri_ext=".nii"
# derivative_path="$wdir_actual/rave-imaging/derivative"
# mri_backup="$wdir_actual/rave-imaging/derivative/MRI_RAW$mri_ext"
#
# # Make sure the actual working directory exists
# fresh_start=0
# if [[ "$fresh_start" -eq 1 && -d "$wdir_actual/rave-imaging/fs" ]]; then
#   rm -r "$wdir_actual/rave-imaging/fs"
# fi
# mkdir -p "$wdir_actual/rave-imaging/derivative"


# Back up original MRI file to derivative folder
cp -f "$mri_path" "$mri_backup"

touch "$derivative_path/conf-reconstruction.yaml"
echo "Heads up: Do NOT edit this file
profile: FreeSurfer Re-construction
work_path: \"$wdir_actual/rave-imaging\"
timestamp: \"$timestamp\"
command:
  execute: recon-all-clinical.sh
  arguments: \"{{ paste(c(args, ""), collapse = " ") }}\"
input_image:
  type: nifti
  path: \"$mri_path\"
  backup: ./derivative/MRI_RAW$mri_ext
  comment: original MRI image file
outputs:
  fs_folder:
    type: directory
    path: ./fs/
    comment: FreeSurfer reconstruction
  normalized_image:
    type: nifti
    path: ./fs/mri/synthSR.norm.nii
    backup: ./derivative/synthSR.norm.nii
    comment: FreeSurfer normalized MRI image
  Norig:
    type: transform
    dimension: 4x4
    transform_from:
      volume: normalized_image
      coordinate_system: IJK
    transform_to:
      space: scanner
      coordinate_system: RAS
    path: ./derivative/transform-Norig.tsv
    comment: From IJK in normalized image to T1 MRI scanner RAS coordinate
  Torig:
    type: transform
    dimension: 4x4
    transform_from:
      volume: normalized_image
      coordinate_system: IJK
    transform_to:
      space: tkr
      coordinate_system: RAS
    path: ./derivative/transform-Torig.tsv
    comment: From IJK in normalized image to FreeSurfer surface RAS coordinate
" > "$derivative_path/conf-reconstruction.yaml"

# Make sure the symlink is done properly
if [[ -d "$wdir_fs" ]]; then
  rm -r "$wdir_fs"
fi
mkdir -p "$wdir_fs"
ln -s "$wdir_actual/rave-imaging" "$wdir_fs"

# Set FreeSurfer home directory & initialize
SUBJECTS_DIR="$wdir_fs/rave-imaging"
{{
  if(length(freesurfer_home) == 1 && !is.na(freesurfer_home) && file.exists(freesurfer_home)) {
    sprintf(
      'FREESURFER_HOME="%s"\nsource "$FREESURFER_HOME/SetUpFreeSurfer.sh"',
      freesurfer_home
    )
  } else { "" }
}}

# rm /Users/dipterix/Library/Caches/org.R-project.R/R/ravecore/FreeSurfer/YAH/rave-imaging/fs/scripts/IsRunning.lh+rh
# arch -x86_64 /bin/tcsh ./inst/shell-templates/recon-all-clinical-core.sh "$wdir_fs/$input_name" fs 7 "$SUBJECTS_DIR"

# Copy Nifti input
cp -f "$mri_path" "$wdir_fs/$input_name"

if [ -f "$SUBJECTS_DIR/fs/scripts/IsRunning.lh+rh" ]; then
  # Use existing FreeSurfer directory to continue analysis
  rm "$SUBJECTS_DIR/fs/scripts/IsRunning.lh+rh"
else
  if [ -d "$SUBJECTS_DIR/fs" ]; then
    rm -r "$SUBJECTS_DIR/fs"
  fi
fi

recon-all-clinical.sh "$wdir_fs/$input_name" fs {{ ncores }} "$SUBJECTS_DIR" | tee -a "$log_file"

# Convert T1.mgz to synthSR.norm.nii so users can choose to use synthSR.norm.nii to coregister
mri_convert --in_type mgz --out_type nii "$SUBJECTS_DIR/fs/mri/synthSR.norm.mgz" "$SUBJECTS_DIR/fs/mri/synthSR.norm.nii"

cp -f "$SUBJECTS_DIR/fs/mri/synthSR.norm.nii" "$derivative_path/synthSR.norm.nii"

# Generate transform matrices
mri_info --vox2ras "$derivative_path/synthSR.norm.nii" > "$derivative_path/transform-Norig.tsv"
mri_info --vox2ras-tkr "$derivative_path/synthSR.norm.nii" > "$derivative_path/transform-Torig.tsv"

# Removing temporary fs root
rm -r "$wdir_fs"

echo "Done." | tee -a "$log_file"

## END OF RAVE Script: FreeSurfer recon-all-clinical.sh ##
