#!/bin/sh
#
# Start or resume a named nap session under screen(1). The screen session
# can be disconnected and later reconnected from another terminal leaving
# nap running and continuing its downloads and uploads for days without
# need of beeing physically logged on the machine.
#
# Copyright (C) 2000  Massimo Dal Zotto <dz@cs.unitn.it>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

case "$1" in
    jazz)
	SERVER=jazz.napster.com:8888
	CFGFILE=~/.nap/jazz.conf
	LOGFILE=~/.nap/download/.jazz.log
	;;
    bebop)
	SERVER=bebop.napster.com:7777
	CFGFILE=~/.nap/bebop.conf
	LOGFILE=~/.nap/download/.bebop.log
	;;
    blues)
	SERVER=blues.napster.com:8888
	CFGFILE=~/.nap/blues.conf
	LOGFILE=~/.nap/download/.blues.log
	;;
    opennap)
	SERVER=johnmerricks.squidcafe.com:8888
	CFGFILE=~/.nap/opennap.conf
	LOGFILE=~/.nap/download/.opennap.log
	;;
    *)
	SERVER=server.napster.com
	CFGFILE=~/.nap/nap.conf
	LOGFILE=~/.nap/download/.nap.log
	;;
esac

if [ ! -x /usr/bin/screen ]; then
    echo "screen is not installed on your system" >&2
    exit 1
fi

pid=$(ps ax | grep -w SCREEN | grep "$SERVER" | head -1 | awk '{print $1}')
if [ ! "$pid" ]; then
    # Start a new screen session in "detached" mode
    echo "starting new session..."
    screen -m -d -S "${1:-napster}" nap -f $CFGFILE -x $LOGFILE -s $SERVER
    sleep 1
    pid=$(ps ax | grep -w SCREEN | grep "$SERVER" | head -1 | awk '{print $1}')
fi

if [ "$pid" ]; then
    # Resumes a running session
    echo "attaching to session $pid"
    exec screen -d -r $pid
else
    echo "session not found" >&2
    screen -ls >&2
    exit 1
fi

# end of file
