#!/bin/sh
# cddbd-start - Starts "cddb" server (cddbd), if necessary
# License:  Public domain (for this file only)
# Revision: 110905

# This script should be executed through "sudo"  (which should be con-
# figured so that all users can run it).

LOOPFILE=__META_LOOPFILE__
MNTDIR=__META_MNTDIR__
LINKDIR=__META_PREFIX__/cddb
SBINDIR=__META_PREFIX__/sbin

umount __META_LOOPFILE__ >& /dev/null
umount __META_MNTDIR__   >& /dev/null

if [ -d $SBINDIR ]; then
    if [ -f $LOOPFILE ]; then
        mkdir -p $MNTDIR
        n=`ls $MNTDIR | wc -l`
        if [ $n == 0 ]; then
            /bin/mount -o loop,ro $LOOPFILE $MNTDIR
            rm -f         $LINKDIR
            ln -s $MNTDIR $LINKDIR
            pause250ms
        fi

        n=`ls $MNTDIR | wc -l`
        if [ $n \!= 0 ]; then
            n=`ps ax | grep "cddbd -s "\$ | wc -l`
            if [ "x$n" == "x0" ]; then
                cd $SBINDIR || exit 1
                PATH=.:$PATH
                cddbd -s 8880 >& /var/log/cddbd &
                pause250ms
            fi
        fi
    else
        if [ x"$BUILDING" == x"yes" ]; then
            rm -f         $LINKDIR
            ln -s $MNTDIR $LINKDIR
            cd $SBINDIR || exit 1
            PATH=.:$PATH
            cddbd -s 8880 >& /var/log/cddbd &
            pause250ms
        fi
    fi
fi

EXTERNAL="freedb\.freedb\.org"
n=`ps ax | grep "cddbd -s " | grep -v grep | wc -l`

if [ "x$n" \!= "x0" ]; then
    sed -e "s|^# *\(127\.0\.0\.1.*$EXTERNAL\)|\1|" -i /etc/hosts
else
    sed -e "s|^\(127\.0\.0\.1.*$EXTERNAL\)|# \1|" -i /etc/hosts
    echo "Error: Couldn't start server"
    exit 1
fi
