#!/bin/sh
########################################################################
#
# arc2orig
#
# Brute force renaming of files from ESO archive file name
# to what is in ORIGNAME keyword (with .fits added if necessary)
#
# Usage:
#    arc2orig filename
# filename can contain path to the file
#
# If file does not exist or is not provided, error with 
# error code 1 occurs.
#
# If file is not a fits file, error with exit code 2 occurs
#
# If ORIGNAME is not present or is not readable from the file
# (e.g. if the script is run on a compressed file) error with 
# exit code 3 occurs.
#
# If a file with ORIGNAME already exists, error with exit
# code 4 occurs (this also prevents renaming file onto intself).
#
# If the user has no write permission in the directory, error
# with exit code 5 occurs.
#
# Unexplained error: exit code 6.
#
# No warranties are assumed or implied. Use at your own risk.
#
# Author: AD
#
########################################################################

### Usage blurb

COMMAND=`basename $0`

if [ $# -lt 1 ] ; then
    echo "Usage: $COMMAND filename"
    exit 1
fi

### Does input file exist?

f=$1
if [ ! -f $f ] ; then
    echo "No file ${f}, exiting"
    exit 1
fi

### Is input file FITS?

issimple=`fold $f | head -1 | strings | cut -c1-6`
if [ "$issimple" != "SIMPLE" ] ; then
    echo "File ${f} is not a valid FITS file, exiting"
    exit 2
fi

### get file directory

d=`dirname $f`


### Get ORIGFILE, exit if not exists

o=`fold $f | head -1000 | strings | grep "^ORIGFILE" | cut -f2 -d"'"`
o=`echo $o`
if [ "$o" = "" ] ; then
    echo "No \(or empty \) ORIGFILE in ${f}, exiting"
    exit 3
fi

### test if you have write permission in the working directory

touch .testfile.removeme.$$ 2> /dev/null
if [ $? -ne 0 ] ; then
    echo "No write permission in the current directory, exiting"
    exit 4
fi

### Is there "fits" in origfile? If not, add it

tescik=`echo $o | grep "fits" | wc -c`
if [ $tescik -eq 0 ] ; then
    o="${o}.fits"
fi
o="${d}/${o}"

### Check whether output file already exists

if [ -f ${o} ] ; then
    echo "Output file already exists, exiting"
    exit 4
fi

### test if you have write permission in the working directory

touch ${d}/.testfile.removeme.$$ 2> /dev/null
if [ $? -ne 0 ] ; then
    echo "No write permission in the directory, exiting"
    exit 5
fi

### Do it

mv ${f} ${o}
if [ $? -ne 0 ] ; then
    echo "Something went wrong"
    exit 6
fi

### Successful finish

exit 0

### ___oOo___
