#!/bin/sh -xe

clear

AUDIOPLAYDEVICE=snd/0.default
AUDIORECDEVICE=snd/0.rec
AUDIOMONDEVICE=snd/0.mon

AUDIOMONPID=X
AUDIORECPID=X

trap rec_stop 1 2 3 6
rec_stop() {
  kill $AUDIORECPID $AUDIOMONPID
}

rec_mon() {
      aucat -f $AUDIOMONDEVICE -o $HOME/work/rec-mon.wav &
      AUDIOMONPID=$!
}

rec_mic() {
      aucat -j on -c 0:0 -o $HOME/work/rec-mic.wav &
      AUDIORECPID=$!
}

rec_screen() {
    echo 'Press q to stop.'
    #ffmpeg  -y \
    #        -loglevel warning \
    #        -hide_banner \
    #        -fflags genpts \
    #        -flags low_delay \
    #        -thread_queue_size 256 \
    #        -framerate 30 \
    #        -f x11grab \
    #        -probesize 16M \
    #        -i :0.0 \
    #        -c:v libx264rgb \
    #        -crf 0 \
    #        -qp 0 -framerate 30 \
    #        -sws_flags neighbor \
    #        -preset ultrafast \
    #        -tune zerolatency \
    #        $HOME/work/rec-screen.mkv
    ffmpeg  -y -loglevel warning -hide_banner \
        -f x11grab -i :0.0 -c:v libx264rgb -crf 0 -qp 0 -framerate 30 -sws_flags neighbor -preset ultrafast -tune zerolatency $HOME/work/rec-screen.mkv \
        -f sndio -i $AUDIORECDEVICE -c:a copy $HOME/work/rec-mic.wav \
        -f sndio -i $AUDIOMONDEVICE -c:a copy $HOME/work/rec-mon.wav
}

#rec_mon
#rec_mic
rec_screen
#rec_stop

sleep 0.5

 sox $HOME/work/rec-mic.wav -n trim 0 5 noiseprof \
     | sox $HOME/work/rec-mic.wav $HOME/work/rec-mic-clean.wav \
       noisered - 0.2 bass 5 contrast
#sox $HOME/work/rec-mic.wav $HOME/work/rec-mic-clean.wav bass 5 contrast

printf "[A]utoencode or [S]hotcut: "
read S

case $S in
    [aA]) rec_encode; ;;
    [sS]) shotcut --noupgrade --fullscreen --clear-recent $HOME/work/rec-screen.mkv $HOME/work/rec-*.wav; ;;
    *) ;;
esac
