#!/bin/bash -x
#  bundle:  group files into a distribution package
#
#  Copyright 2010, Sugar Labs
#  Frederick Grose <fgrose@sugarlabs.org>
#
#  adapted from 'The Unix Programming Environment'
#            by Brian W. Kernighan and Rob Pike
#            (Englewood Cliffs, NJ : Prentice-Hall, 1984) p. 98
#
#  Usage:
#       bundle <[@]file1> <file2> [<file3> ... <fileN>] [@bundleFile]
#
#       ./bundleFile [options or arguments for file1]
#
#       The first command line produces the bundle of input files when the
#       >bundleFile name option is provided with the '@' prefix.  Otherwise,
#       the files are echoed to stdout.
#
#       The second command line results in the unbundling of the files into
#       the working directory.   file1 may be prefixed with '@' to signal that
#       it should be launched after the unbundling.
#       
#  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; version 2 of the License.
#
#  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 Library General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

export PS4='+(${LINENO}:${BASH_SOURCE}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'

# Set up this bundling process (process special @arguments)
bundleFile="${@: -1:1}"
if [[ "${bundleFile:0:1}" = "@" ]]; then
    bundleFile=$(basename "${bundleFile#\@}")
    : > "$bundleFile"
    su --session-command="chmod +x $bundleFile" root
    set "${@:1:(($#-1))}"
else
    bundleFile=":"
fi

if [[ "${1:0:1}" = "@" ]]; then
    scriptToLaunch="${1#\@}"
    shift
    set "$scriptToLaunch" $*
    scriptToLaunch=$(basename "$scriptToLaunch")
fi

# Build bundleFile
echo -e "#!/bin/bash -x
#
# To unbundle, bash this file.
#" >> $bundleFile

echo 'bundleFileDirectory=$( dirname "$( readlink -f $0 )" )' >> $bundleFile

for i
do
    bname=$(basename $i)
    echo 'su --session-command="rm -f ${bundleFileDirectory}/'$bname' " root' \
        >> $bundleFile
    echo "cat >$bname  <<'End of $bname' " >> $bundleFile
    cat $i >> $bundleFile
    echo "End of $bname" >> $bundleFile
    echo 'su --session-command="mv -fT '$bname '${bundleFileDirectory}/'$bname'\
        &> /dev/null " root' >> $bundleFile
    echo 'su --session-command="chmod +x ${bundleFileDirectory}/'$bname' " \
        root' >> $bundleFile
done

if [[ -n "$scriptToLaunch" ]]; then
    echo 'thisScriptPath=$( readlink -f $0 )' >> $bundleFile
    echo 'su --session-command="${bundleFileDirectory}/'${scriptToLaunch} \
        '$thisScriptPath $@" root' >> $bundleFile
fi


