#!/bin/sh
#
# Script to create a new GRASS LOCATION from a raster data set
#
# Markus Neteler 2002, ITC-irst, Trento
#
# This program is free software under the GNU GPL (>=v2).
# No warranty. Use at your own risk.
#
# The trick:
#  It generates a temp LOCATION for a fake GRASS session, then
#  uses r.in.gdal to generate the target LOCATION with new raster
#  data set.


#customize, if needed:
STARTSCRIPT=grass5

####################nothing to change below:
MAP=$1
LOCATION=$2
MYGISDBASE=$3

if [ $# -lt 2 ] ; then
 echo "Script to create a new LOCATION from a raster data set"
 echo "Usage:"
 echo "   create_location.sh rasterfile newlocation_name [GISDBASE]"
 echo ""
 echo "rasterfile: file to be imported (tiff, EOSAT, gif, jpeg...)"
 echo "newlocation_name: new location to be created"
 echo "GISDBASE: full path to GRASS database directory (optional)"
 echo "          e.g. $HOME/grassdata"
 echo ""
 exit 1
fi

if test -f $HOME/.gislock5 ; then
 echo "ERROR. GRASS 5.0 is already running"
 echo "Please close other session first."
 exit 1
fi

#get GISBASE from GRASS start script:
STARTSCRIPTPATH=`type -p $STARTSCRIPT`
if [ "$STARTSCRIPTPATH" = "" ] ; then
 echo "ERROR. Cannot find '$STARTSCRIPT' in path"
 exit 1
fi

GISBASE=`cat $STARTSCRIPTPATH | grep 'GISBASE=' | cut -d'=' -f2`
if [ "$GISBASE" = "" ] ; then
 echo "ERROR. Cannot get GISBASE from '`type -p $STARTSCRIPT`' script"
 exit 1
fi

#get GISDBASE from previous session:
if [ "$MYGISDBASE" = "" ] ; then
  GISDBASE=`grep GISDBASE $HOME/.grassrc5 | cut -d' ' -f2`
  if [ "$GISDBASE" = "" ] ; then
   echo "ERROR. Cannot get GISDBASE from $HOME/.grassrc5"
   echo "Please specify the GISDBASE parameter"
   exit 1
  fi
else
 GISDBASE=$MYGISDBASE
fi

if test -d $GISDBASE/$LOCATION ; then
 echo "ERROR. Location $LOCATION already exists in $GISDBASE"
 exit 1
fi

#generate temporal LOCATION:
TEMPDIR=$$.tmp
mkdir -p $GISDBASE/$TEMPDIR/temp

#save existing .grassrc5
if test -e $HOME/.grassrc5 ; then
   mv $HOME/.grassrc5 /tmp/$TEMPDIR.grassrc5
fi
echo "LOCATION_NAME: $TEMPDIR" >  $HOME/.grassrc5
echo "MAPSET: temp"            >> $HOME/.grassrc5
echo "DIGITIZER: none"         >> $HOME/.grassrc5
echo "GISDBASE: $GISDBASE"     >> $HOME/.grassrc5

export GISBASE=$GISBASE
export GISRC=$HOME/.grassrc5
export PATH=$PATH:$GISBASE/bin:$GISBASE/scripts

# import raster map into new location
r.in.gdal in=$MAP out=$MAP location=$LOCATION
if [ $? -eq 1 ] ; then
  echo "An error occured. Stop."
  exit 1
fi

#restore previous .grassrc5
if test -f /tmp/$TEMPDIR.grassrc5 ; then
   mv /tmp/$TEMPDIR.grassrc5 $HOME/.grassrc5
fi

#cleanup:
rm -rf $GISDBASE/$TEMPDIR

echo "Launch GRASS now with:"
echo " grass5 -text $GISDBASE/$LOCATION/PERMANENT"
