#!/bin/bash
# vim: set sts=4 sw=4 et :

set -e

if [[ -z $DISPLAY ]]; then
    echo "Need \$DISPLAY to connect to X server!"
    exit 1
fi

LOADED_MODULES=()
COMBINED_SINK_NAME="combined"
SOURCE_VOIP=$(pactl stat | sed -n -e "s/Default Sink: \(.*\)/\1/p").monitor
SOURCE_MIC=$(pactl stat | sed -n -e "s/Default Source: \(.*\)/\1/p")

# Pulseaudio doesn't have a module to combine multiple sources into one,
# so we emulate it by routing it through a null sink, and monitoring that
module_combine_sources() {
    echo "Seting up null sink"
    LOADED_MODULES+=($(pactl load-module module-null-sink \
        sink_name="$COMBINED_SINK_NAME"))
    echo "Connecting VoIP source to null sink"
    LOADED_MODULES+=($(pactl load-module module-loopback \
        source_dont_move=true sink_dont_move=true \
        sink="$COMBINED_SINK_NAME" source="$SOURCE_VOIP"))
    echo "Connecting Default source to null sink"
    LOADED_MODULES+=($(pactl load-module module-loopback \
        source_dont_move=true sink_dont_move=true \
        sink="$COMBINED_SINK_NAME" source="$SOURCE_MIC"))
}

unload_modules() {
    set +e
    for each in ${LOADED_MODULES[@]}; do
        pactl unload-module $each
    done
}

main() {
    local regex='s/.*current \([0-9]\+\) x \([0-9]\+\),.*/\1x\2/p'
    local screen_size=$(xrandr -q | sed -n -e "$regex")
    local outdir="$HOME/Videos/Screencasts/"
    mkdir -p "$outdir"
    avconv -s:v "$screen_size" \
        -f x11grab -i "$DISPLAY" \
        -f pulse -i "${SOURCE_NAME}" \
        "$outdir/$(date +%Y%m%d-%H%M%S).mkv"
}

trap unload_modules EXIT

if [[ $1 == 1 || $1 == voip ]]; then
    SOURCE_NAME="$SOURCE_VOIP"
elif [[ $1 == 2 || $1 == me ]]; then
    SOURCE_NAME="$SOURCE_MIC"
else
    SOURCE_NAME="${COMBINED_SINK_NAME}.monitor"
    module_combine_sources
fi

main
