#! /bin/bash
#
# NOTE: This script is only of interest for the DOSEMU developers and
#	distributors, who want to built their packages.
#
# This generates the dosemu part (dosemu-<version>-bin.tgz of the dosemu
# binary distribution. Read README.bindist for details on hoe 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=../src/plugin/commands

BLIST="dosemu.bin dosdebug"
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 ist not supported for the bindist.
  removing the s-bit from the copy.
"
fi


mkdir -p $TMP
cp -p ../README.bindist dosemu $TMP
ln -sf dosemu $TMP/xdosemu

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

cp -p ../etc/vga.pcf $TMP/Xfonts

cp -p ../etc/global.conf dosemurc $TMP/conf
perl -pe \
 's/^(\$_debug\s+=\s+\"-a)/$1+c/;s/^(\$_rdtsc\s+=\s+\()on/$1off/;s/^(\$_dpmi\s+=\s+\()off/${1}0x2000/' \
 ../etc/dosemu.conf > $TMP/conf/dosemu.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,comcom}.com $TMP/freedos/dosemu
chmod 644 $TMP/freedos/dosemu/{generic,comcom}.com
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
