#!/bin/sh
#	BSDI	audiocompose,v 1.3 1997/06/22 16:10:10 jch Exp
#
# Copyright (c) 1991 Bell Communications Research, Inc. (Bellcore)
# 
# Permission to use, copy, modify, and distribute this material 
# for any purpose and without fee is hereby granted, provided 
# that the above copyright notice and this permission notice 
# appear in all copies, and that the name of Bellcore not be 
# used in advertising or publicity pertaining to this 
# material without the specific, prior written permission 
# of an authorized representative of Bellcore.  BELLCORE 
# MAKES NO REPRESENTATIONS ABOUT THE ACCURACY OR SUITABILITY 
# OF THIS MATERIAL FOR ANY PURPOSE.  IT IS PROVIDED "AS IS", 
# WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
#

unset IFS

# Defaults
RECORD_AUDIO=${RECORD_AUDIO:-vrec}
PLAY_AUDIO=${PLAY_AUDIO:-vplay}
EDIT_AUDIO=${EDIT_AUDIO:-mxv}

usage() { echo "Usage: audiocompose mimetype audiofile" 1>&2; }

if [ $# -ne 2 ]; then usage; exit 1; fi

AudioType=$1
AudioFile=$2

process_alive() {
    /bin/kill -0 ${1} > /dev/null 2>&1
    return ${?}
}

kill_process() {
    if process_alive ${1}; then
	/bin/kill -1 ${1} > /dev/null 2>&1
	sleep 2
	process_alive ${1} && /bin/kill -9 ${1} > /dev/null 2>&1
    fi
}

record() {
    read -p "Press RETURN when you are ready to start recording: " ignored_input

    if [ "${AudioType}" = "audio/basic" ]; then
	cat /dev/audio > "${AudioFile}" &
    else
	${RECORD_AUDIO} ${1+"${@}"} > "${AudioFile}" &
    fi
    PID=${!}
    jobs -l

    trap 'kill_process ${PID}' 0 1 2 15
    read -p "press RETURN when you are done recording: " ignored_input
    sleep 1

    if process_alive ${PID}; then
	echo -n "Killing recording job ${PID}... "
	kill_process ${PID}
	echo ""
	process_alive ${PID} && echo "WARNING: Could not kill ${PID}"
    fi
    trap 0 1 2 15
}

whatnow() {
    echo "Options are:"
    echo "  p)layback [${PLAY_AUDIO}_args]"
    echo "  r)eplace [${RECORD_AUDIO}_args]"
    echo "  e)dit [sound_editor [editor_args]]: Default ${EDIT_AUDIO}"
    echo "  s)end"
    echo "  q)uit [-delete]"
    echo ""
    read -p "What now? " which
    set ${which}

    case ${1} in
	[pP]*) shift; ${PLAY_AUDIO} ${1+"${@}"} "${AudioFile}"; ;;
	[rR]*) shift; record ${1+"${@}"}; ;;
	[eE]*) shift;
	       if [ ${#} -gt 0 ]; then
		   EDIT_AUDIO="${1:-${EDIT_AUDIO}}"; shift;
	       fi
	       ${EDIT_AUDIO} ${1+"${@}"} "${AudioFile}"; ;;
	[sS]*) exit 0; ;;
	[qQ]*) shift;
	       case ${1} in -d*|d*) rm -f "${AudioFile}"; ;; esac
	       exit 1; ;;
	*)     echo "${*} unknown command"; ;;
    esac
}

# Don't record by default unless $AudioFile doesn't exist or is empty
if [ ! -s "${AudioFile}" ]; then record; fi

while true; do whatnow; done
exit 1
