#!/usr/bin/env bash
# $Id$
#
# Thomas Dreibholz's PlanetLab Script Collection
# Copyright (C) 2005-2023 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com

# Bash options:
set -e


. ./planetlab-config


SERVER=$1
if [ x$SERVER = "x" ]; then
   SERVER=$PLANETLAB_COMPILEHOST
   echo "NOTE: Using compile host $SERVER."
fi


echo -e "\x1b[34m`env LANG=en date`: Preparing source package ...\x1b[0m"
rm -rf $DISTNAME-bin.tar.bz2 bin/

workDir=`pwd`
cd ../..
rm -f *.tar.gz   # Remove old versions!
make dist
if [ ! -e $DISTNAME.tar.gz ] ; then
   echo "ERROR: Unable to create distribution $DISTNAME! Is this the correct version?"
   exit 1
fi


echo -e "\x1b[34m`env LANG=en date`: Contacting $SERVER ...\x1b[0m"
cat $DISTNAME.tar.gz | ssh -C -i $PLANETLAB_KEY -oPasswordAuthentication=no -oStrictHostKeyChecking=no $PLANETLAB_USER@$SERVER "\
echo -e \"\\x1b[33m\`env LANG=en date\`: Transfering archive to $SERVER ...\\x1b[0m\" && \
cat > /tmp/$DISTNAME.tar.gz && \
echo -e \"\\x1b[33m\`env LANG=en date\`: Unpacking archive on $SERVER ...\\x1b[0m\" && \
rm -rf $DISTNAME && \
tar xzf /tmp/$DISTNAME.tar.gz && \
rm -f /tmp/$DISTNAME.tar.gz && \
echo -e \"\\x1b[33m\`env LANG=en date\`: Configuring archive on $SERVER ...\\x1b[0m\" && \
cd $DISTNAME && \
./configure --disable-shared --enable-static --enable-test-programs --with-glib=/usr $DISTCONFOPT && \
echo -e \"\\x1b[33m\`env LANG=en date\`: Compiling archive on $SERVER ...\\x1b[0m\" && \
make && \
echo -e \"\\x1b[33m\`env LANG=en date\`: Packaging binaries on $SERVER ...\\x1b[0m\" && \
cd $DISTDIRNAME && \
mkdir bin && \
cp -f $DISTPRGS bin/ && \
cd bin && \
if [ $DISTSTRIP != 0 ] ; then \
echo -e \"\\x1b[33mStripping binaries ...\\x1b[0m\" ; \
echo "$DISTPRGS" | xargs -n1 strip ; \
fi && \
cd .. && \
tar cvf - bin | bzip2 -c9 >$DISTNAME-bin.tar.bz2"


echo -e "\x1b[34m`env LANG=en date`: Downloading binary archive from $SERVER ...\x1b[0m"
cd "$workDir"
scp -i $PLANETLAB_KEY $PLANETLAB_USER@$SERVER:$DISTNAME/$DISTDIRNAME/$DISTNAME-bin.tar.bz2 .
tar xjvf $DISTNAME-bin.tar.bz2
