#! /bin/bash
#
# NOTE: This script is only of interest for the DOSEMU developers and
#	distributors, who want to build their packages.
#
# This generates the dosemu part (dosemu-<version>-bin.tgz) of the dosemu
# binary distribution. Read README.bindist for details on how to use the
# generated output.
#
# Usage:
#
#   $ cd ./dist
#   $ ./mkbindist  [ targetdir_where_to_put_the_tarball ] [owner]
#

TARBALLDIR=$1
TARBALLOWNER=$2

umask 022
TMPBASE=tmp
rm -rf $TMPBASE
TMP=$TMPBASE/dosemu
BIN=../bin
SYS=../commands
COM=../commands

BLIST="dosemu.bin dosdebug libplugin_*.so"
SLIST="aspi.sys cdrom.sys ems.sys emufs.sys fossil.com mgarrot.com"

if [ ! -x $BIN/dosemu.bin ]; then
  echo "
  No compiled DOSEMU available.
  You first need to do 'make' from the dosemu source dir.
  ... giving up.
"
  exit 1
fi

if [ ! -f $SYS/ems.sys ]; then
  echo "
  No compiled DOSEMU support files available, compiling it now ..."
  hereIam=`pwd -P`
  cd ..
  if ! make dosbin; then
    echo "
  could not compile the DOSEMU support files
  ... giving up
"
    exit 1
  fi
  cd $hereIam
fi


if [ -u $BIN/dosemu.bin ]; then
  echo "
  You made dosemu.bin suid, this is not supported for the bindist.
  removing the s-bit from the copy.
"
fi


mkdir -p $TMP
cp -p ../README.bindist ../COPYING ../COPYING.DOSEMU $TMP
cp -p dosemu.bindist $TMP/dosemu
tail -n +9 dosemu >> $TMP/dosemu
chmod 755 $TMP/dosemu
ln -sf dosemu $TMP/xdosemu
ln -sf freedos $TMP/drive_z
ln -sf drive_z/dosemu $TMP/commands

mkdir -p $TMP/bin
mkdir -p $TMP/conf
mkdir -p $TMP/Xfonts
mkdir -p $TMP/freedos/dosemu

cp -p ../etc/*.pcf.gz $TMP/Xfonts
cp -p ../etc/dosemu.alias $TMP/Xfonts/fonts.alias
cp -p ../etc/fonts.dir $TMP/Xfonts/fonts.dir

cp -p ../etc/dosemu.conf $TMP/conf/dosemurc
cp -p ../etc/global.conf $TMP/conf/global.conf

for i in $BLIST; do
  cp -p $BIN/$i $TMP/bin
  strip $TMP/bin/$i
  chmod 755 $TMP/bin/$i
done

for i in $SLIST; do
  cp -p $SYS/$i $TMP/freedos/dosemu
  chmod 644 $TMP/freedos/dosemu/$i
done

cp -p $COM/generic.com $TMP/freedos/dosemu
cp -p config.emu $TMP/freedos
cp -p autoemu.bat $TMP/freedos
cp -p config.sys $TMP/conf
cp -p autoexec.bat $TMP/conf
chmod 644 $TMP/freedos/dosemu/generic.com
chmod 644 $TMP/freedos/config.emu $TMP/freedos/autoemu.bat 
chmod 644 $TMP/conf/config.sys $TMP/conf/autoexec.bat 
LINKLIST=`(cd $COM; for i in *.com; do if [ -L $i ]; then echo -n " $i";fi;done)`
for i in $LINKLIST; do
  ln -sf generic.com $TMP/freedos/dosemu/$i
done

if [ -n "$TARBALLDIR" ]; then
  if [ ! -d $TARBALLDIR ]; then
    echo "
    Directory $TARBALLDIR does not exist
"
    exit
  fi
  if [ -n "$TARBALLOWNER" -a $UID = "0" ]; then
    chown -R $TARBALLOWNER $TMP
  fi
  VER=`cat ../VERSION`
#  VER=`strings $TMP/bin/dosemu.bin|perl -ne '/Version: dosemu-(\S+)\s+versioncode/ and print"$1\n"'`
  tar -cf- -C tmp dosemu |gzip -9 >$TARBALLDIR/dosemu-${VER}-bin.tgz
fi
