#!/bin/sh
# $Id: pulse_clean,v 1.2 2015-03-31 12:26:09 pc161604 Exp $
# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
# 
# Leave pulse_audio as we found it

[ -x "/usr/bin/nawk" ] && AWK="nawk" || AWK="awk"

pidproc() {
  ps -u $2 -o pid -o args | grep $1 |
  $AWK '($2 ~ PROCNAME) { print $1 }' PROCNAME=$1
}

DISPLAY_ID=`echo $DISPLAY | cut -f2 -d ':' | cut -f1 -d '.'`

# Tidy up gstreamer
# Find latest version
GSTREAMER_HOME=`ls -d $HOME/.gstreamer-*.* | tail -1`
if [ -n "${GSTREAMER_HOME}" ] ; then
  rm ${GSTREAMER_HOME}/registry.*.bin > /dev/null 2>&1
fi

PROC=`pidproc /usr/bin/pulseaudio $TTA_UID`
if [ -n "${PROC}" ]; then
  SSINDEX=`pacmd list-sinks | $AWK 'BEGIN {INDEX=0} $1 ~ /index:/ {INDEX=$2} $2 ~ /<sgdout.'$DISPLAY_ID'>/ {SINDEX=INDEX} $1 ~ /module:/ {if (SINDEX == INDEX) MINDEX=$2;} END {print MINDEX}'`
  if [ -n "${SSINDEX}" ] ; then
    pacmd unload-module $SSINDEX > /dev/null
  fi

  SSINDEX=`pacmd list-sinks | $AWK 'BEGIN {INDEX=0} $1 ~ /index:/ {INDEX=$2} $2 ~ /<sgdin.'$DISPLAY_ID'>/ {SINDEX=INDEX} $1 ~ /module:/ {if (SINDEX == INDEX) MINDEX=$2;} END {print MINDEX}'`
  if [ -n "${SSINDEX}" ] ; then
    pacmd unload-module $SSINDEX > /dev/null
  fi
fi
