#!/bin/sh

## This file is part of Moonlight Creator
##   Copyright (C) 1996-1998  Stephane Rehel
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU Library General Public
## License as published by the Free Software Foundation; either
## version 2 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
## Library General Public License for more details.
##
## You should have received a copy of the GNU Library General Public
## License along with this library; if not, write to the Free
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

set -e

# Syntax:
#
#  make_dll lib_name.dll objects...
#
# WARNING! Assert `dirname $1` == "." !!!!

dll_basename=`basename $1 .dll`
dll_name=$1
shift
objects=$*

# From:
#  Example Script to compile and link a relocatable DLL
#    Files that make up the DLL = foo.c foo2.c init.cc fixup.c.
#        (init.cc and fixup.c are housekeeping routines needed for the DLL. The actual
#                      library routines are in foo.c and foo2.c)

# ***Fill in your path to libcygwin.a here (with no trailing slash)***
LIBPATH=/Cygnus/B19/H-i386-cygwin32/i386-cygwin32/lib

init_filename=/tmp/init

cat > $init_filename.c << EOF
#include <windows.h> 
#include <cygwin32/cygwin_dll.h>
int WINAPI moonlight_dll_entry( HANDLE h, DWORD r, void* ptr )
{
  return 1;
}
DECLARE_CYGWIN_DLL(moonlight_dll_entry);
EOF

gcc -o $init_filename.o -c $init_filename.c
rm $init_filename.c

fixup_filename=/tmp/fixup

cat >$fixup_filename.c << EOF
	asm(".section .idata\$3\n" ".long 0,0,0,0, 0,0,0,0");

EOF

gcc -o $fixup_filename.o -c $fixup_filename.c
rm $fixup_filename.c

objects="$objects $init_filename.o $fixup_filename.o"

# Make .def file:
echo EXPORTS > $dll_basename.def
nm $objects | grep '^........ [T] _' | sed 's/[^_]*_//' >> $dll_basename.def 

ENTRY=__cygwin32_dll_entry
LIBS="$LIBPATH/libcygwin.a $LIBPATH/libkernel32.a"
LD_FLAGS="--image-base=0x0800000"

# Link DLL.
ld $LD_FLAGS --base-file $dll_basename.base --dll -o $dll_basename.dll $objects $LIBS -e ${ENTRY}@12
dlltool --as=as --dllname $dll_basename.dll --def $dll_basename.def --base-file $dll_basename.base --output-exp $dll_basename.exp
ld $LD_FLAGS --base-file $dll_basename.base $dll_basename.exp --dll -o $dll_basename.dll $objects $LIBS -e ${ENTRY}@12
dlltool --as=as --dllname $dll_basename.dll --def $dll_basename.def --base-file $dll_basename.base --output-exp $dll_basename.exp
ld $LD_FLAGS $dll_basename.exp --dll -o $dll_basename.dll $objects $LIBS -e ${ENTRY}@12

# Build the $dll_basename.a lib to link to:
dlltool --as=as --dllname $dll_basename.dll --def $dll_basename.def --output-lib $dll_basename.a

# et voila!

rm $init_filename.o $fixup_filename.o
