#! /bin/tcsh -f

#
# mkfsdist
#
# Usage: mkfsdist sourcedir targetdir platform [options]
#
# Purpose: creates a FreeSurfer distribution from sourcedir in the targetdir
# specified on the command-line. The distribution can be installed
# by following the instructions in freesurfer/INSTALL.
#
# Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR
# CVS Revision Info:
#    $Author: nicks $
#    $Date: 2007/01/06 00:01:14 $
#    $Revision: 1.34 $
#
# Copyright (C) 2002-2007,
# The General Hospital Corporation (Boston, MA).
# All rights reserved.
#
# Distribution, usage and copying of this software is covered under the
# terms found in the License Agreement file named 'COPYING' found in the
# FreeSurfer source code root directory, and duplicated here:
# https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferOpenSourceLicense
#
# General inquiries: freesurfer@nmr.mgh.harvard.edu
# Bug reports: analysis-bugs@nmr.mgh.harvard.edu
#


# TO MAKE THE DISTRO:

# - Create the target directory, something like freesurfer-DATE/. this
#   is the destination directory. For example, ~/work/freesurfer-20030512/.

# - Copy freesurfer_dev or freesurfer_alpha to a new directory called
#   freesurfer/. For example, ~/work/freesurfer-20030512/freesurfer/.

# - Run mkfsdist:
#    $ mkfsdist ~/work/freesurfer-20030512/freesurfer
#           ~/work/freesurfer-20030512 PLATFORM
#   with appropriate substitutions. PLATFORM can be Linux or Darwin
#   or Solaris.

# - mkfsdist will fill ~/work/freesurfer-20030512 with tarballs and other
#   files. Tar up this directory:
#    $ tar cfzv freesurfer-20030512-Linux.tar.gz ~/work/freesurfer-20030512
#   with appropriate OS name in the tarball name.


#
# These files are created in the target directory:
#  INSTALL            -- installation instructions (copied from source dir);
#  license.freesurfer -- license agreement (copied from source dir);
#  freesurfer.tar.gz  -- the freesurfer tree
#  minc.tar.gz        -- ~inverse/minc (for running functional autoreg)
#  talairach.tar.gz   -- $SUBJECTS_DIR/talairach (MNI 305)
#  bert.raw.tar.gz
#  bert.recon.tar.gz
#  bert.func.tar.gz
#  average7.tar.gz    -- contains average labels for checking spherical morph
#
# Symbolic Links in freesurfer:
#
#  It does not follow symbolic links, so any symbolic link
#  in the source dir must have a pointer relative to someplace in the
#  source dir tree.
#
# Dynamic and Statically Linked Programs
#
#  The only programs that are dynamically linked are tksurfer, tkmedit,
#  and tkregister. These programs are replaced by their statically
#  linked counterparts. The dynamically linked programs are included
#  with a .dynamic extension. The process that does this is fairly
#  involved. See comments in the code for more detail.
#
# Excluding files and directories from freesurfer:
#
#  Files and directories within the freesurfer tree can be targeted
#  for exclusion by entering them into freesurfer/tar-exclude. This
#  is useful for excluding the license file (.license) as well as other
#  files that just take up space. When adding items to the exclude file,
#  put only one name on each line and make sure there are no trailing
#  white spaces. This name will be exluded where ever it is found in the
#  tree, either as a file or as a directory.  It will also exclude the
#  files found in tar-exclude-more and tar-exclude-gca.
#
#
set VERSION = '$Id: mkfsdist,v 1.34 2007/01/06 00:01:14 nicks Exp $';

# To include the autoseg in the distribution set environment varible
# KEEPAUTOSEG to 1 before running mkfsdist (ie, setenv KEEPAUTOSEG 1)
if(! $?KEEPAUTOSEG ) setenv KEEPAUTOSEG 0
if($KEEPAUTOSEG) then
   echo "INFO: keeping autoseg"
else
   echo "INFO: NOT keeping autoseg"
endif

# Bert data locations.
set BERT_ANAT_DIR = $SUBJECTS_DIR/bert
set BERT_ORIG_DIR = $BERT_ANAT_DIR/mri/orig
set BERT_FUNC_DIR = /space/sake/5/tutorial/JUL01/bert-functional

# If they can't find the original dirs to tar up, look here for
# pretarred versions of the bert data.
set BERT_ANAT_TARRED = ~kteich/work/bert.recon.tar.gz
set BERT_ORIG_TARRED = ~kteich/work/bert.raw.tar.gz
set BERT_FUNC_TARRED = ~kteich/work/bert.func.tar.gz

set AVERAGE7_DIR = $SUBJECTS_DIR/average7


#------------------------------------------------------#
if($#argv < 3) then
  echo "USAGE: mkfsdist sourcedir targetdir platform [options]"
  echo ""
  echo "   sourcedir: usually freesurfer_alpha or freesurfer_dev"
  echo "   targetdir: dir in which to create archive"
  echo "    platform: platform for whose binaries will be included"
  echo "              either Linux, Darwin, or Solaris"
  echo ""
  echo "   options include:"
  echo "     --no-compress, --compress: create or don't create a gzipped tarfile (default yes)"
  echo "   the following specify which components to include:"
  echo "     --no-freesurfer, --freesurfer (default yes)"
  echo "     --no-auto-seg, --auto-seg (default no)"
  echo "     --no-average, --average (default yes)"
  echo "     --no-minc, --minc (default yes)"
  echo "     --no-talairach, --talairach (default yes)"
  echo "     --no-bert-raw, --bert-raw (default yes)"
  echo "     --no-bert-recon, --bert-recon (default yes)"
  echo "     --no-bert-func, --bert-func (default yes)"
  echo "     --no-data: equivalent to --no-average, --no-minc, --no-talairach, --no-bert-*"
  echo ""
  echo "Ex: mkfsdist ~/work/freesurfer ~/work/freesurfer-030512 Linux --auto-seg"
  echo ""
  exit 1;
endif

set SOURCE_DIR = $argv[1];
set TARGET_DIR = $argv[2];
set PLATFORM = $argv[3];

set COMPRESS   = 1
set AUTO_SEG   = 0
set MAIN_TREE  = 1
set AVERAGE    = 1
set MINC       = 1
set TALAIRACH  = 1
set BERT_RAW   = 1
set BERT_RECON = 1
set BERT_FUNC  = 1
set OVERRIDE_SRC_CHECK = 0
foreach option ($argv)
  switch ("$option")
    case "--no-compress":
      set COMPRESS = 0
      breaksw
    case "--no-freesurfer":
      set MAIN_TREE = 0
      breaksw
    case "--auto-seg":
      set AUTO_SEG = 1
      breaksw
    case "--no-average":
      set AVERAGE = 0
      breaksw
    case "--no-minc":
      set MINC = 0
      breaksw
    case "--no-talairach":
      set TALAIRACH = 0
      breaksw
    case "--no-bert-raw":
      set BERT_RAW = 0
      breaksw
    case "--no-bert-recon":
      set BERT_RECON = 0
      breaksw
    case "--no-bert-func":
      set BERT_FUNC = 0
      breaksw
    case "--override-src-check":
      set OVERRIDE_SRC_CHECK = 1
      breaksw
    case "--no-data":
      set AVERAGE = 0
      set TALAIRACH = 0
      set BERT_FUNC = 0
      set BERT_RAW = 0
      set BERT_RECON = 0
      breaksw
  endsw
end


# Check the platform argument #
if( "$PLATFORM" != "Linux" && "$PLATFORM" != "Darwin" && "$PLATFORM" != "Solaris") then
  echo "ERROR: this platform not supported."
  exit 1;
endif

# Check if the source dir's name is freesurfer #
if( "`basename $SOURCE_DIR`" != "freesurfer" && ! $OVERRIDE_SRC_CHECK ) then
    echo "ERROR: Source dir is not */freesurfer"
    echo "       This means that the tarball created will not have the"
    echo "       directory name, and the INSTALL instructions will be"
    echo "       incorrect."
    echo ""
    echo "       To make a distribution, copy freesurfer_dev or _alpha"
    echo "       to a directory called freesurfer/, and run this script"
    echo "       on that directory."
    echo ""
    echo "       For more instructions, look at the source for this"
    echo "       script."
    exit 1;
endif

# Check that source dir is there #
if(! -e $SOURCE_DIR) then
  echo "ERROR: cannot find $SOURCE_DIR"
  exit 1;
endif

# Check that test subject runs are there #
if( ( $BERT_RAW || $BERT_RECON ) && ! -e $BERT_ANAT_DIR) then
  if(! -e $BERT_ORIG_TARRED ) then
    echo "ERROR: cannot find $BERT_ANAT_DIR"
  exit 1;
  endif
  echo "WARNING: cannot find $BERT_ANAT_DIR, using $BERT_ORIG_TARRED"
endif

if( $BERT_RAW ) then
  foreach run (1 2 3)
    set rundir = `printf %s/%03d $BERT_ORIG_DIR $run`;
    if( ! -e $rundir ) then
      if(! -e $BERT_ORIG_TARRED ) then
        echo "ERROR: cannot find $rundir"
        exit 1
      endif
      echo "WARNING: cannot find $rundir, using $BERT_ORIG_TARRED"
    endif
  end
endif

if( $BERT_FUNC && ! -e $BERT_FUNC_DIR) then
  if(! -e $BERT_FUNC_TARRED ) then
    echo "ERROR: cannot find $BERT_FUNC_DIR"
  exit 1;
  endif
  echo "WARNING: cannot find $BERT_FUNC_DIR, using $BERT_FUNC_TARRED"
endif

# Check that the average7 is there #
if( $AVERAGE && ! -e $AVERAGE7_DIR) then
  echo "ERROR: cannot find $AVERAGE7_DIR"
  exit 1;
endif

# Check that the talairach subject is there #
if( $TALAIRACH && ! -e $SUBJECTS_DIR/talairach) then
  echo "ERROR: cannot find $SUBJECTS_DIR/talairach"
  exit 1;
endif

# This is where the MNI stuff lives #
if( $MINC && ! -e /space/lyon/9/pubsw) then
  echo "ERROR: cannot find /space/lyon/9/pubsw"
  exit 1;
endif


echo " "
echo "Creating FreeSurfer Distribution in $TARGET_DIR"
echo " "

# Create the target directory #
mkdir -p $TARGET_DIR
if($status) then
  echo "ERROR: could not create $TARGET_DIR"
  exit 1;
endif

# Get the full path of the target directory #
pushd $TARGET_DIR  > /dev/null
set TARGET_DIR = `pwd`;
popd > /dev/null

# Make sure the target dir is not inadvertently set to
# freesurfer_alpha
if("$TARGET_DIR" == "$SOURCE_DIR") then
  echo "ERROR: target dir == source dir"
  exit 1;
endif

# Put a file with the date as name in the target dir
set DateStr = "`date '+%Y%m%d'`"
touch $TARGET_DIR/$DateStr

# Create a log file #
set LF = ${PWD}/mkfsdist-$PLATFORM-$DateStr.log
if(-e $LF) mv $LF $LF.old
echo "Log file is $LF"

echo "Log file for FreeSurfer distribution creation" >> $LF
echo $VERSION  >> $LF
echo "$0"    >> $LF
echo "$argv" >> $LF
date >> $LF

# ---- Tar up source dir ------- #
if( $MAIN_TREE ) then

  pushd $SOURCE_DIR > /dev/null
  cd ..

  set SOURCE_DIR_REL = `basename $SOURCE_DIR`

  # Create the exclude file for the freesurfer source dir. Basically we
  # want to exclude platform-specific binary and lib directories and any
  # backup or temp files (i.e. README~, tkmedit.031402)
  set EXCLUDE_FILE = /tmp/exclude
  rm -f $EXCLUDE_FILE
  if( "$PLATFORM" != "Linux" ) then
    find $SOURCE_DIR_REL | grep Linux >> $EXCLUDE_FILE
  endif
  if( "$PLATFORM" != "Darwin" ) then
    find $SOURCE_DIR_REL | grep Darwin >> $EXCLUDE_FILE
  endif
  if( "$PLATFORM" != "Solaris" ) then
    find $SOURCE_DIR_REL | grep Solaris >> $EXCLUDE_FILE
  endif
  find $SOURCE_DIR_REL | grep Linux2 >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL | grep IRIX >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL | grep SunOS >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name \*.03\* >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name \*.02\* >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name \*.01\* >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name \*~ >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name \#\*\# >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name \*.bu >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name \*.bak >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name \*.log >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name \*.old >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name .xdebug\* >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name tar-exclude >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name tar-exclude-more >> $EXCLUDE_FILE

  # For the distribution, we exclude the UpdateFromSnapshot.sh script
  # and UPDATE instructions.
  find $SOURCE_DIR_REL -name UpdateFromSnapshot.sh >> $EXCLUDE_FILE
  find $SOURCE_DIR_REL -name UPDATE >> $EXCLUDE_FILE

  # Add on the other exclude files.
  if( -e $SOURCE_DIR/tar-exclude ) then
    cat $SOURCE_DIR/tar-exclude >> $EXCLUDE_FILE
  endif
  if( -e $SOURCE_DIR/tar-exclude-more ) then
    cat $SOURCE_DIR/tar-exclude-more >> $EXCLUDE_FILE
  endif
  if( -e $SOURCE_DIR/tar-exclude-gca && ! $KEEPAUTOSEG) then
    cat $SOURCE_DIR/tar-exclude-gca >> $EXCLUDE_FILE
  endif


  echo "--------------------------------------------" | tee -a $LF
  echo "Tarring $SOURCE_DIR" | tee -a $LF
  date | tee -a $LF
  set TF = $TARGET_DIR/freesurfer.tar
  rm -f $TF
  set tarcmd = ( tar cv -f $TF  $SOURCE_DIR_REL --exclude-from $EXCLUDE_FILE )
  echo $tarcmd | tee -a $LF
  $tarcmd  >> $LF

  rm -f $EXCLUDE_FILE

  date | tee -a $LF


  #--- Special for tksurfer, tkmedit, and tkregister in freesurfer_alpha ---#
  # Note: static vs dynamic only applies to Linux.
  # This part assures that the statically linked versions of tksurfer,
  # tkmedit, and tkregister are the default in the Linux distribution.
  # In the NMR version (ie, ~inverse/freesurfer_alpha), these programs are
  # dynamically linked, and the static version have a .static extension.
  # Also, tksurfer is replaced by tksurfer.new in all OSs; note that there
  # will still be tksurfer.new.
  #
  # NMR Center          Linux                Sun/IRIX
  # ------------------  -----------------    --------------
  # tkmedit             tkmedit.dynamic      tkmedit
  # tkmedit.static      tkmedit              N/A
  # tkregister          tkregister.dynamic   tkregister
  # tkregister.static   tkregister           N/A
  # tksurfer            Excluded             Excluded
  # tksurfer.new        tksurfer.new         tksurfer.new
  # tksurfer.new        tksurfer.dynamic     tksurfer
  # tksurfer.new.static tksurfer             N/A
  # tksurfer.new.static tksurfer.new         N/A
  #
  # A temporary freesurfer_alpha is created in the target
  # directory, and, under that, bin/Linux is created.
  # The relevant files are copied according to
  # the translation described above. This freesurfer_alpha is appended
  # to the tar of the original freesurfer_alpha. The temporary
  # freesurfer_alpha is then deledted, and the tar file is compressed.
  # When the distribution is extracted, the static versions will
  # overwrite the dynamic version (though there will be .dynamic and
  # .static files there).
  if( "`basename $SOURCE_DIR`" == "freesurfer_alpha" ) then

    echo "------------------------------------------" | tee -a $LF
    echo "Handling tkmedit, tksurfer, and tkregister" | tee -a $LF
    date | tee -a $LF
    pushd $TARGET_DIR > /dev/null
    set FSA_TMP_DIR = freesurfer_alpha;
    mkdir -p $FSA_TMP_DIR

    # Go through each OS - actually only applies to Linux #
    foreach OS (Linux)

      # tkmedit and tkregister #
      mkdir -p $FSA_TMP_DIR/bin/$OS
      foreach binary (tkmedit tkregister)
        # Copy dynamic #
        set fdynamic = $SOURCE_DIR/bin/$OS/$binary
        if(! -e $fdynamic) then
          echo "ERROR: cannot find $fdynamic"| tee -a $LF
          exit 1;
        endif
        cp $fdynamic $FSA_TMP_DIR/bin/$OS/$binary.dynamic
        # Copy static #
        set fstatic = $SOURCE_DIR/bin/$OS/$binary.static
        if(! -e $fstatic) then
          echo "ERROR: cannot find $fstatic"| tee -a $LF
          exit 1;
        endif
        cp $fstatic  $FSA_TMP_DIR/bin/$OS/$binary
      end # foreach binary (tkmedit tkregister)

    end#foreach OS

    # ----------- Handle tksurfer ----------------------#
    foreach OS (Linux Solaris IRIX)
      mkdir -p $FSA_TMP_DIR/bin/$OS

      # Get path to tksurfer.new
      set tksurfernew = $SOURCE_DIR/bin/$OS/tksurfer.new
      if(! -e $tksurfernew) then
        echo "ERROR: cannot find $tksurfernew"| tee -a $LF
        exit 1;
      endif

      # Copy tksurfer.new to tksurfer (except Linux) #
      if("$OS" != "Linux") then
        # Solaris and IRIX
        cp $tksurfernew $FSA_TMP_DIR/bin/$OS/tksurfer
        cp $tksurfernew $FSA_TMP_DIR/bin/$OS/tksurfer.new
      else
        # Linux - must handle stat/dyn linked version #
        cp $tksurfernew $FSA_TMP_DIR/bin/$OS/tksurfer.dynamic
        cp $tksurfernew $FSA_TMP_DIR/bin/$OS/tksurfer.new.dynamic
        # Copy tksurfer.new.static to tksurfer (Linux only)#
        set tksurfernew_static = $SOURCE_DIR/bin/$OS/tksurfer.new.static
        if(! -e $tksurfernew_static) then
          echo "ERROR: cannot find $tksurfernew_static"| tee -a $LF
          exit 1;
        endif
        cp $tksurfernew_static  $FSA_TMP_DIR/bin/$OS/tksurfer
        cp $tksurfernew_static  $FSA_TMP_DIR/bin/$OS/tksurfer.new
      endif

    end #foreach OS

    echo "Appending temporary freesurfer_alpha to tar `date`"| tee -a $LF
    tar rv -f $TF ./$FSA_TMP_DIR >> $LF

    echo "Removing temporary directory `date`"| tee -a $LF
    rm -rf $FSA_TMP_DIR

  endif # specials for freesurfer_alpha #

  echo "Compressing tar file `date`"| tee -a $LF
  gzip $TF

endif

#----- Tar up average7 --------#
if ( $AVERAGE ) then

  echo "--------------------------------------------" | tee -a $LF
  date | tee -a $LF
  pushd $AVERAGE7_DIR > /dev/null
  cd ..
  echo "Tarring average7 data" | tee -a $LF
  set TF = $TARGET_DIR/average7.tar.gz
  rm -f $TF
  tar cvz -f $TF \
    ./average7/mri \
    ./average7/label/??-avg_*.label \
    ./average7/surf/?h.avg_curv \
    ./average7/surf/?h.avg_sulc \
    ./average7/surf/?h.curv \
    ./average7/surf/?h.inflated \
    ./average7/surf/?h.orig \
    ./average7/surf/?h.pial \
    ./average7/surf/?h.smoothwm \
    ./average7/surf/?h.sphere \
    ./average7/surf/?h.sphere.reg \
    ./average7/surf/lh.rh.sphere.reg \
    ./average7/surf/?h.sulc >> $LF
  date | tee -a $LF

endif

#-- Tar up the minc bin and libs -------#
if( $MINC ) then
    echo "--------------------------------------------" | tee -a $LF
    echo "Tarring minc" | tee -a $LF
    date | tee -a $LF
    pushd /space/lyon/9/pubsw > /dev/null
    set TF = $TARGET_DIR/minc.tar.gz
    rm -f $TF
    # Look for the right mni package. If found, tar it.
    set mni_platform = $PLATFORM
    if( "$PLATFORM" == "Linux" ) then
	set mni_platform = Linux2
    endif
    if( "$PLATFORM" == "Darwin" ) then
	set mni_platform = MacOS10.2
    endif
    if( "$PLATFORM" == "Solaris" ) then
	set mni_platform = Solaris
    endif
    set mnidir = $mni_platform/packages
    if(! -e $mnidir) then
	echo "WARNING: cannot find $mnidir" | tee -a $LF
    else
        pushd $mnidir > /dev/null
	tar cvz -f $TF mni >> $LF
    endif
    date | tee -a $LF
endif

#----- Tar up the talairach (MNI305) subject --------#
if( $TALAIRACH ) then
    echo "--------------------------------------------" | tee -a $LF
    echo "Tarring talairach subject" | tee -a $LF
    pushd $SUBJECTS_DIR/talairach > /dev/null
    cd ..
    date | tee -a $LF
    set TF = $TARGET_DIR/talairach.tar.gz
    rm -f $TF
    tar cvz -f $TF ./talairach >> $LF
    date | tee -a $LF
endif

#----- Tar up berts raw anatomicals --------#
if( $BERT_RAW ) then
    echo "--------------------------------------------" | tee -a $LF
    date | tee -a $LF
    if( -e $BERT_ORIG_DIR ) then
      pushd $BERT_ORIG_DIR > /dev/null
      pawd
      set TF = $TARGET_DIR/bert.raw.tar.gz
      rm -f $TF
      tar cvz -f $TF ./001 ./002 ./003 >> $LF
    else
      cp $BERT_ORIG_TARRED $TARGET_DIR
    endif
endif

#----- Tar up berts reconstructed anatomicals --------#
if( $BERT_RECON ) then
    echo "--------------------------------------------" | tee -a $LF
    date | tee -a $LF
    if( -e $BERT_ANAT_DIR ) then
      pushd $BERT_ANAT_DIR > /dev/null
      cd ..
      pawd
      set TF = $TARGET_DIR/bert.recon.tar.gz
      rm -f $TF
      tar cvz -f $TF ./bert >> $LF
    else
      cp $BERT_ANAT_TARRED $TARGET_DIR
    endif
endif

#----- Tar up Bert's functional data --------#
if( $BERT_FUNC ) then
    echo "--------------------------------------------" | tee -a $LF
    date | tee -a $LF
    if( -e $BERT_FUNC_DIR ) then
      pushd $BERT_FUNC_DIR > /dev/null
      cd ..
      echo "Tarring bert functional data" | tee -a $LF
      set TF = $TARGET_DIR/bert.func.tar.gz
      rm -f $TF
      tar cvz -f $TF ./bert-functional >> $LF
      date | tee -a $LF
    else
      cp $BERT_FUNC_TARRED $TARGET_DIR
    endif
endif

echo "------------------------------------------" | tee -a $LF

# Copy the INSTALL File
cp $SOURCE_DIR/INSTALL $TARGET_DIR

# Copy the License Agreement File
cp $SOURCE_DIR/docs/license.freesurfer $TARGET_DIR

echo "$0 done"


exit 0
