#!/bin/sh

CHICKEN_ROOT=/usr/local/chicken-4.7.0/
CHICKEN_BIN_VER=6
DEPLOY_DIR=/tmp/chick/deploy
TMP_DIR=/tmp/chick/p

EGG_LIST='html-parser intarweb loops matchable openssl posix-extras regex sha2 spiffy-uri-match sql-de-lite ssql uri-common srfi-19 hmac'
LOCAL_EGG_DIR=~/project/local-eggs
LOCAL_EGG_LIST='spiffy knodium-sessions boyd waffle'



TMP_REPO=$TMP_DIR/lib/chicken/$CHICKEN_BIN_VER
ORIG_DIR=$PWD


# Prepare the staging area
mkdir -p $TMP_REPO/
chicken-install -i $TMP_REPO/

# Install the public eggs and all their dependencies
CHICKEN_REPOSITORY=$TMP_REPO chicken-install $EGG_LIST

# Install the local eggs and all their dependencies
for e in $LOCAL_EGG_LIST; do
	cd $LOCAL_EGG_DIR/$e/
	CHICKEN_REPOSITORY=$TMP_REPO chicken-install
done
cd $ORIG_DIR/

# Prepare the deployment area
mkdir -p $DEPLOY_DIR/
chicken-install -i $DEPLOY_DIR/
cp -r $CHICKEN_ROOT/lib/libchicken.* $DEPLOY_DIR/

# Deploy the public eggs and the public dependencies of both public eggs and
# local eggs.
make chicken-deploy-eggs
DEPLOY=`./chicken-deploy-eggs --dry-run $TMP_DIR/ $DEPLOY_DIR/`
export LD_LIBRARY_PATH=$DEPLOY_DIR # socket egg fails without this
export CHICKEN_REPOSITORY=$TMP_REPO
$DEPLOY

# Deploy the local eggs
for e in $LOCAL_EGG_LIST; do
	cd $LOCAL_EGG_DIR/$e/
	chicken-install -deploy -prefix $DEPLOY_DIR/
done
cd $ORIG_DIR/

# Deploy the application binaries
make mrproper
ls | sort > $TMP_DIR/orig.list
make
ls | sort > $TMP_DIR/built.list
APP_LIST=`diff $TMP_DIR/orig.list $TMP_DIR/built.list | grep ^\> | sed -e 's/^> //'`
for f in $APP_LIST; do
	cp -a $f $DEPLOY_DIR/
done
cd $ORIG_DIR/

# Deploy the application resources
cp -a web/ $DEPLOY_DIR/
for d in `ls -d *.app`; do
	if [ -d $d/resources/ ]; then
		mkdir $DEPLOY_DIR/$d/
		cp -a $d/resources $DEPLOY_DIR/$d/
	fi
done

