#!/bin/sh

# Like mkdir -p, but the actual space is on the scratch disk.
# One difference is that it leaves an empty directory - it clears the space
# if it already exists.
# Use rmscratch.sh to get rid of the space.

# Note that the scratch space mirrors your directory tree, so you can get
# collisions if you run it from your home directory.

# Where is the root of the scratch space?
SCRATCH=/scratch/$USER

deldir () {
if mv $1 $1.junk
then
  rm -rf $1.junk  &
else
  rm -rf $1
fi
}

pwd=''
for d in $*
do
  if test /${d#/} = $d
  then		# If this is an absolute path
    da=$d
  else		# A relative path
    if test -z "$pwd"
    then	# Find out where we are, if we don't know already.
      pwd=$(pwd)
    fi
    da=$pwd/$d		# Make the path absolute
  fi

  if test -h "$d"
  then			# This is a symbolic link
    # Clear the scratch location:
    deldir "$SCRATCH$da"
  elif test -d "$d"
  then	# It's a regular directory
    deldir "$d"
  else	# It's something else, presumably a file
    rm -f "$d"
  fi

  # Make the directory in scratch space and symbolic-link to it.
  sd="$SCRATCH$da"
  mkdir -p "$sd"
  if ! ln -s "$SCRATCH$da" $d
  then	# Couldn't link to the scratch disk.   Back off and make a directory here.
    rmdir "$sd" &
    mkdir -p "$d"
  fi
done
wait
