#!/bin/bash

KDIR=/usr/src/linux
if [ "x$1" != "x" ]; then
  KDIR="$1"
fi
KADIR=$KDIR/drivers/sound
ADIR=$PWD/..
if [ "x$2" != "x" ]; then
  ADIR="$2"
fi

function copy_file () {
	ln -svf $ADIR/$1 $KADIR/$2
}

function copy_dir () {
	pushd $PWD > /dev/null
	cd $ADIR/$1
	mkdir -p $KADIR/$2
	if [ -r Makefile.k ]; then
		ln -svf $ADIR/$1/Makefile.k $KADIR/$2/Makefile
	fi
	if [ "$1" != "lowlevel" ]; then
		for i in *.[ch]; do
			ln -svf $ADIR/$1/$i $KADIR/$2/$i
		done
	fi
	popd > /dev/null
}

function copy_include_dir () {
	pushd $PWD > /dev/null
	cd $ADIR/$1
	for i in *.h; do
		rm -f $KDIR/include/sound/$i
		ln -svf $ADIR/$1/$i $KDIR/include/sound
	done
	popd > /dev/null
}

if [ ! -r $ADIR/kernel/sound.c ]; then
  echo "Can't find ALSA sources..."
  exit
fi
if [ ! -r $KDIR/drivers/sound/sound_core.c ]; then
  echo "Can't find kernel sources..."
  exit
fi

pushd $PWD > /dev/null
#cd $KDIR
#if grep CONFIG_SND Makefile > /dev/null; then
#  echo "Makefile already modified"
#else
#  cp -av Makefile Makefile.old
#  cat $ADIR/utils/patches/patch.Makefile.top.2.4.1 | patch -p0
#  echo "Makefile patched"
#fi
cd $KDIR/drivers/sound
if grep alsa Makefile > /dev/null; then
  echo "drivers/sound/Makefile already modified"
else
  cp -av Makefile Makefile.old
  cat $ADIR/utils/patches/patch.Makefile.2.4.2 | patch -p0
  echo "drivers/sound/Makefile patched"
fi
if grep "Advanced Linux Sound Architecture" Config.in > /dev/null; then
  echo "drivers/sound/Config.in already modified"
else
  echo >> Config.in
  echo "mainmenu_option next_comment" >> Config.in
  echo "comment 'Advanced Linux Sound Architecture'" >> Config.in
  echo >> Config.in
  echo "tristate 'Advanced Linux Sound Architecture' CONFIG_SND" >> Config.in
  echo "if [ \"\$CONFIG_SND\" != \"n\" ]; then" >> Config.in
  echo "  source drivers/sound/Alsa-Config.in" >> Config.in
  echo "fi" >> Config.in
  echo >> Config.in
  echo "endmenu" >> Config.in
  echo "drivers/sound/Config.in patched"
fi
mkdir -p alsa
cd $ADIR/utils
make
./snd-deps --configin > $KDIR/drivers/sound/Alsa-Config.in
#copy_file Makefile.k Makefile
mkdir -p $KDIR/include/sound
rm -rf $KDIR/include/sound/*.h
copy_include_dir include
rm -f $KDIR/include/sound/config.h
rm -f $KDIR/include/sound/config1.h
copy_dir kernel alsa
copy_dir kernel/seq alsa/seq
copy_dir kernel/seq/instr alsa/seq/instr
copy_dir kernel/seq/oss alsa/seq/oss
copy_dir kernel/oss alsa/oss
copy_dir lowlevel lowlevel
copy_dir lowlevel/generic lowlevel/generic
copy_dir lowlevel/isa lowlevel/isa
copy_dir lowlevel/pci lowlevel/pci
copy_dir lowlevel/i2c lowlevel/i2c
copy_dir lowlevel/gus lowlevel/gus
copy_dir lowlevel/sb lowlevel/sb
copy_dir lowlevel/emu10k1 lowlevel/emu10k1
copy_dir cards cards
copy_dir cards/ppc cards/ppc
popd > /dev/null
