#!/bin/sh
# This is a trick to re-execute this script using gtcl, but adding the
# path of the current script to $PATH first.  It works because backslashes
# are recognized by Tcl at the end of comment lines but not by shell.
# \
exec env PATH=$PATH:`dirname $0` gtcl $0 "$@"

# The rest of the script is Tcl

# 2023-11-15: Added -thorough option
# 2023-04-21: Now gives more details if there is a crash.
# 2016-01-13: Changed to use .find_script
# 2015-10-08: Added -nosubjectids option

source [.find_script process_util.tcl]
set mode "turbo"

set argnum 0
set start_frame ""
set end_frame ""
set no_subject_ids 0
set combine_target 0

while {1} {
  set arg [lindex $argv $argnum]
  if {$arg=="-notrack"} {
    set mode "none"
    incr argnum
  } elseif {$arg == "-thorough"} {
    incr argnum
    set mode "thorough"
  } elseif {$arg=="-start"} {
    incr argnum
    set start_frame [lindex $argv $argnum]
    incr argnum
  } elseif {$arg=="-end"} {
    incr argnum
    set end_frame [lindex $argv $argnum]
    incr argnum
  } elseif {$arg=="-nosubjectids"} {
    incr argnum
    set no_subject_ids 1
  } else {
    break
  }
}

if {$argc-$argnum!=1} {
  puts stderr ""
  puts stderr {Usage: process_project [<options>] <project>}
  puts stderr ""
  puts stderr "Options:"
  puts stderr "  -notrack"
  puts stderr "  -thorough"
  puts stderr "  -start <frame>"
  puts stderr "  -end <frame>"
  puts stderr "  -nosubjectids"
  puts stderr ""
  exit 1
}

proc abspath {path} {
  set cwd [pwd]
  cd [file dirname $path]
  set path_dir [pwd]
  cd $cwd
  return [file join $path_dir [file tail $path]]
}

set project_path [abspath [lindex $argv $argnum]]
set ids_file [project_id_data $project_path]

if {![file exists $project_path]} {
  puts stderr "Missing $project_path"
  exit 1
}

if {[file exists $ids_file]} {
  if {$start_frame==""} {
    set start_frame 1
  }
}

proc update_path_env {} {
  global env
  set exe_dir [file dirname [file readlink "/proc/self/exe"]]
  set env(PATH) "$env(PATH):$exe_dir"
}

update_path_env

set error_code [
  catch {
    process_project \
      $project_path \
      forward \
      $start_frame \
      $end_frame \
      $mode \
      $combine_target \
      $no_subject_ids
  } message
]

if {$error_code} {
  puts stderr "process_project failed: $message"
  puts stderr $errorInfo
  exit 1
}

