#!/bin/sh

PERMTYPE=`echo __MVC_PERMTYPE__ | sed -e 's/\(.\).*/\1/' | tr a-z A-Z`

if [ "x`whoami`" = xroot ]
then
	if test "x$PERMTYPE" = x -o "x$PERMTYPE" = xM
	then
		CATUSER=__MVC_CATUSER__
		CATGROUP=__MVC_CATGROUP__
	elif test "x$PERMTYPE" = xG
	then
		CATUSER=__MVC_INTERCHANGEUSER__
		CATGROUP=__MVC_CATGROUP__
	else
		CATUSER=__MVC_INTERCHANGEUSER__
		CATGROUP=__MVC_INTERCHANGEGROUP__
	fi
fi

if test "x$PERMTYPE" = x -o "x$PERMTYPE" = xM -o "x$PERMTYPE" = xG
then
	DMODE=2770
	FMODE=660
else
	DMODE=700
	FMODE=600
fi

# Link the image directory always
ln -s __MVC_IMAGEDIR__ __MVC_RELOCATE____MVC_CATROOT__

# Make log directories to store logs.
if test -n '__MVC_LOGDIR__'
then 
	LOGDIR='__MVC_LOGDIR__'
	mkdir -p     __MVC_RELOCATE__$LOGDIR/logs
	mkdir -p     __MVC_RELOCATE__$LOGDIR/orders
	touch        __MVC_RELOCATE__$LOGDIR/error.log
	ln    -s     $LOGDIR/error.log __MVC_RELOCATE____MVC_CATROOT__
	ln    -s     $LOGDIR/logs      __MVC_RELOCATE____MVC_CATROOT__
	ln    -s     $LOGDIR/orders    __MVC_RELOCATE____MVC_CATROOT__
	chmod $DMODE __MVC_RELOCATE__$LOGDIR/logs
	chmod $DMODE __MVC_RELOCATE__$LOGDIR/orders
	touch        __MVC_RELOCATE__$LOGDIR/error.log
	if test -n "$CATUSER"
	then
		[ -n "$CATUSER"  ] && chown $CATUSER  __MVC_RELOCATE__$LOGDIR/error.log
		[ -n "$CATGROUP" ] && chgrp $CATGROUP __MVC_RELOCATE__$LOGDIR/error.log
	fi
else
	LOGDIR='__MVC_CATROOT__'
	mkdir -p     __MVC_RELOCATE__$LOGDIR/orders
	mkdir -p     __MVC_RELOCATE__$LOGDIR/logs
	chmod $DMODE __MVC_RELOCATE__$LOGDIR/logs
	chmod $DMODE __MVC_RELOCATE__$LOGDIR/orders
	touch        __MVC_RELOCATE__$LOGDIR/error.log
	if test -n "$CATUSER"
	then
		[ -n "$CATUSER"  ] && chown $CATUSER  __MVC_RELOCATE__$LOGDIR/error.log
		[ -n "$CATGROUP" ] && chgrp $CATGROUP __MVC_RELOCATE__$LOGDIR/error.log
	fi
fi

chmod $FMODE __MVC_RELOCATE__$LOGDIR/error.log
chmod $FMODE __MVC_RELOCATE____MVC_CATROOT__/catalog.cfg

# Make cache directories to store tmps.
if test -n '__MVC_CACHEDIR__'
then 
	CACHEDIR='__MVC_CACHEDIR__'
	mkdir -p __MVC_RELOCATE__$CACHEDIR/session
	ln    -s $CACHEDIR/session __MVC_RELOCATE____MVC_CATROOT__
	mkdir -p __MVC_RELOCATE__$CACHEDIR/tmp
	ln    -s $CACHEDIR/tmp     __MVC_RELOCATE____MVC_CATROOT__
else
	CACHEDIR='__MVC_CATROOT__'
	mkdir -p     __MVC_RELOCATE__$CACHEDIR/session
	mkdir -p     __MVC_RELOCATE__$CACHEDIR/tmp
	chmod $DMODE __MVC_RELOCATE__$CACHEDIR/session
	chmod $DMODE __MVC_RELOCATE__$CACHEDIR/tmp
fi

# Fix directory ownership if running as root
if test -n "$CATUSER"
then
	for i in $LOGDIR/logs $LOGDIR/orders $CACHEDIR/session $CACHEDIR/tmp
	do
		[ -n "$CATUSER"  ] && chown $CATUSER __MVC_RELOCATE__$i
		[ -n "$CATGROUP" ] && chgrp $CATGROUP __MVC_RELOCATE__$i
	done
fi
