#!/bin/sh


list_alternatives() {
cat <<EOF
gem-plugin-glfw3	70 gemdefaultwindow.pd gemdefaultwindow-glfw3.pd
gem-plugin-sdl		70 gemdefaultwindow.pd gemdefaultwindow-sdl.pd
gem-plugin-glut		70 gemdefaultwindow.pd gemdefaultwindow-glut.pd
gem			50 gemdefaultwindow.pd gemdefaultwindow-glx.pd
EOF
}

build_alternatives () {
list_alternatives  | while read pkg prio name alt; do
  cat > debian/${pkg}.alternatives <<EOF
Name: ${name}
Link: /usr/lib/pd/extra/Gem/${name}
Alternative: /usr/lib/pd/extra/Gem/${alt}
Priority: ${prio}
EOF
done
}

#build_alternatives; exit $?

echo "NOTE: with dh>=13.1 there's a new dh_installalternatives" 1>&2
echo "see $0 for more info" 1>&2

INFILE=debian/alternatives
BASEDIR=/usr/lib/pd/extra/Gem
DOLLAR1='$1'

make_postinst() {
cat <<EOL
#! /bin/sh

set -e

#DEBHELPER#

EOL

 egrep "^$1[ 	]" "${INFILE}" | while read pkg priority dst src
 do
   echo "        update-alternatives --install ${BASEDIR}/${dst} ${dst} ${BASEDIR}/${src} ${priority}"
 done

cat <<EOL

exit 0
EOL
}

make_prerm() {
cat <<EOL
#!/bin/sh -e

set -e

#DEBHELPER#

case "$DOLLAR1" in
    (remove|deconfigure)
EOL

 egrep "^$1[ 	]" "${INFILE}" | while read pkg priority dst src
 do
   echo "        update-alternatives --remove ${dst} ${BASEDIR}/${src}"
 done

cat <<EOL
    ;;
    (upgrade)
    ;;

    (failed-upgrade)
    ;;

    (*)
        echo "prerm called with unknown argument \\\`$DOLLAR1'" >&2
        exit 0
    ;;
esac

exit 0
EOL
}


make_alternative() {
   make_postinst $1 > debian/$1.postinst
   make_prerm $1 > debian/$1.prerm
}


cat ${INFILE} | sed -e 's|#.*||' | grep . | awk '{print $1}' | sort -u | while read pkg
do
 make_alternative $pkg
done
