#!/bin/sh

###################################################
# Copyright 2019-2022 VMware, Inc.  All rights reserved.
###################################################

need_restart=yes

if ! pulseaudio --check >/dev/null 2>&1; then
   # pulseaudio daemon does not exist.
   need_restart=no
elif [ -n "$XDG_RUNTIME_DIR" ]; then
   # Check if the pulseaudio daemon belongs to this session.
   pa_pid=$(cat "$XDG_RUNTIME_DIR"/pulse/pid 2>/dev/null)
   if [ -n "$pa_pid" ]; then
      pa_disp=$(cat /proc/$pa_pid/environ | tr '\0' '\n' | awk -F '=' '/DISPLAY=/ {print $2}')
      if [ -n "$pa_disp" ] && [ -n "$DISPLAY" ] && . /usr/lib/vmware/viewagent/commonlib.sh; then
         pa_disp_num=$(extract_xdisplay_number $pa_disp)
         display_num=$(extract_xdisplay_number $DISPLAY)
         if [ "$pa_disp_num" != -1 ] && [ "$display_num" != -1 ] &&
               [ "$pa_disp_num" = "$display_num" ]; then
            need_restart=no
         fi
      fi
   fi
fi

if [ "$need_restart" = yes ]; then
   pulseaudio --kill

   # If pulseaudio does not start automatically, we should wait for
   # pulseaudio to be ready before running start-pulseaudio-x11 to
   # make sure it loads the modules successfully.
   for i in $(seq 10); do
      sleep 1

      # Check pulseaudio process first, to avoid pactl triger new
      # pulseaudio process quickly.
      pulseaudio --check >/dev/null 2>&1
      if [ "$?" = "0" ]; then
         if [ -f "/usr/bin/pactl" ]; then
            /usr/bin/pactl info >/dev/null 2>&1 && break
         else
            break
         fi
      elif [ -f "/usr/bin/pactl" ]; then
         # Try to trigger autospawn if possible
         /usr/bin/pactl info >/dev/null 2>&1
      fi

      if [ "$i" = "10" ]; then
         echo "pulseaduio doesn't ready for start-pulseaudio-x11"
      fi
   done
fi

exec start-pulseaudio-x11
