#!/usr/bin/perl
#
# rec - record audio data with prompting
#
# Usage: rec [-help] [-(no)pause] [file]
#
# Author: Jerry Sweet <jsweet@irvine.com>
#
# $Header: /sparc/users/jsweet/notes/mime/tutorial/rec.sparc,v 1.2 1993/03/17 00:45:05 jsweet Exp $

#
# Subprograms
#

sub barf {
  print STDERR "$prog: ", @_, "\n";
  exit 1;
}


sub endit {
  # Come here on a TERM (^C) signal.

  if ($child_pid) {
    kill 15, $child_pid;
    wait;
  }

  if ($file) {
    close(STDOUT);
    close(OUT);
  }

  exit 0;
}

#
# Main
#


($prog = $0) =~ s|.*/||;

$pause = 1;

while ($_ = shift @ARGV) {
  /^-help$/ && do {
      print STDERR <<"xxEndHelpxx";
$prog - record audio data with prompting
Usage: $prog [-help] [-(no)pause] [file]
Options:
  -help       print this help message
  -nopause    don't prompt; just do it
  -pause      prompt and wait for Return [default]
xxEndHelpxx

      exit 1;
    };

  /^-nopause$/ && do { --$pause; next; };
  /^-pause$/ && do { ++$pause; next; };

  /^[^\-]/ && do { $file = $_; next; };

  &barf("unrecognized command line option \"$_\"");
}

$pause = $pause > 0;

select(STDERR);
$| = 1;	# make stderr unbuffered.
select(STDOUT);

@rec_args = ('record');

if ($file) {
  open(OUT, ">$file") || &barf("can't create \"$file\" - $!");
  open(STDOUT, ">&OUT") || &barf("can't dup stdout to \"$file\" - $!");
}
else {
  if (-t STDOUT) {
    &barf("you need to specify a file or redirect stdout");
  }
}

if (! $pause) {
  $SIG{'TERM'} = 'endit';
  exec "@rec_args";
  &barf("exec of \"@rec_args\" failed");
}

print STDERR "Press Return to start...";
$wait = <STDIN>;

$child_pid = fork;

if ($child_pid == 0) {
  # We're in the child.
  exec "@rec_args";
  &barf("(in child) exec of \"@rec_args\" failed");
}
else {
  if ($child_pid < 0) {
    # Fork failed.
    &barf("problem forking - $!");
  }
  else {
    # We're in the parent.
    print STDERR "Press Return to end...";
    $wait = <STDIN>;
    kill 15, $child_pid;
    wait;
  }
}

if ($file) {
  close(STDOUT);
  close(OUT);
}

exit 0;
