#!/bin/csh -f
#+
# newdir -- create a new output directory for DEIMOS images
#
# Purpose:
#	Generate an output directory based on the account name and
#	the UT date.  Select the data disk with the most disk space 
#	if no disk number is provided.  Create the output directory if
#	it does not yet exist.  Verify that it is a directory and that 
#	the user has write access to it.  Redefine OUTDIR keyword
#	appropriately.
#
# Usage:
#	newdir [disk]
# 
# Arguments:
#	disk	1-digit number of the desired data disk
# 
# Output:
#	Feedback is written to standard output
# 
# Side effcts:
#	The OUTDIR keyword in the "deiccd" keyword library is changed
# 
# Restrictions:
#	None
# 
# Exit values:
#	0 = normal completion
#	1 = wrong number of arguments
#	3 = invalid datadisk argument
#	4 = could not create directory
#	5 = desired output directory exists, but is not a directory
#	6 = you do not have write access to the suggested outdir
#
# Example:
#	1) generate a new output directory for DEIMOS images on 
#	   disk /sdata1001:
#		newdir 1
#
#	2) Generate a new output directory for DEIMOS images
#	   on the data disk with the most available space:
#		newdir
#-
# Modification history:
#	2002-Aug-26	GDW	Original version
#	2002-Oct-18	GDW	Changes to support /sdata
#       2003-May-29     GDW     Make data directory group-writeable
#-----------------------------------------------------------------------
set buf = $0
set cmd = $buf:t
set usage = "Usage: $cmd [disk]"

# verify args...
if ( $#argv > 1 ) then
    echo "$usage"
    exit 1
endif

# grab args...
if ( $#argv >= 1 ) then
    @ disk = $1
    shift
endif

# parse disk arg...
if ( $?disk ) then
    set datadisk = /sdata100$disk
else
    # if no disk has been defined, select largest data disk... 
    set buf = `~deimos/bin/disks -n`
    set datadisk = $buf[1]
endif

# verify disk...
if( ! -e $datadisk ) then
    beep
    echo "ERROR: There is no disk ${datadisk}"
    exit 3
endif

# define disk...
set ut_date = `ut_date`
set outdir = ${datadisk}/${USER}/$ut_date

if ( ! -e $outdir ) then
    mkdir $outdir
    if ( $status > 0 ) then
	beep
	echo "ERROR: Could not create directory $outdir"
	exit 4
    else
	echo "Directory $outdir has been created for you"
    endif
endif

if ( ! -d $outdir ) then
    beep
    echo "ERROR: Suggested outdir $outdir exists, but is not a directory"
    exit 5
endif

if ( ! -w $outdir ) then
    beep
    echo "ERROR: You do not have write access to my suggested outdir $outdir"
    exit 6
endif

# make the directory group-writeable...
chmod g+w $outdir

# make the mods...
modify -service deiccd outdir=$outdir silent
echo "Setting outdir to $outdir"