#!/bin/bash

exit_hook()
{
    local pid_sleep=$1
    local unit=$2
    local file_pipe=$3
    systemctl --user stop $unit
    kill $pid_sleep
    rm -f $file_pipe
}

get_file_pipe()
{
    local conf
    local fname_regex
    local default_fname=/run/termidesk/.tera-audio-source
    if pulseaudio --check &>/dev/null
    then
        # pulseaudio
        conf=/etc/pulse/default.pa.d/10-tera-record.pa
        fname_regex='.*file=\([^[:space:]]\+\).*'
    else
        # pipewire
        conf=/etc/pipewire/pipewire.conf.d/10-tera-record.conf
        fname_regex='.*pipe\.filename.*=.*"\([^[:space:]]\+\)".*'
    fi
    local rv=$(sed -n "s/$fname_regex/\1/p" $conf)
    if [[ -n "$rv" ]]
    then
        echo "got file=$rv from conf '$conf'" 1>&2
        echo $rv
    else
        echo "fail get file from conf '$conf'" 1>&2
        echo "use default file '$default_fname'" 1>&2
        echo $default_fname
    fi
}

check_pw_defaults()
{
    if [[ ! -f ~/.local/state/wireplumber/default-nodes ]]
    then
        echo "pipewire (${USER}): set defaults"
        pw-metadata 0 default.configured.audio.source '{ "name": "tera_audio_input" }'  'Spa:String:JSON'
        pw-metadata 0 default.configured.audio.sink   '{ "name": "tera_audio_output" }' 'Spa:String:JSON'
        pw-metadata 0 default.audio.source '{ "name": "tera_audio_input" }'  'Spa:String:JSON'
        pw-metadata 0 default.audio.sink   '{ "name": "tera_audio_output" }' 'Spa:String:JSON'
    else
        echo "pipewire (${USER}): defaults are already set"
    fi
}

# Извлечь имя файла канала из конфига звуковой подсистемы,
# передать в юнит для запуска демона и зачистить старый.
file_pipe=$(get_file_pipe)
echo "FILE_PIPE=$file_pipe" > /run/termidesk/.tera-record-service.env
chmod 0666 /run/termidesk/.tera-record-service.env

rm -f $file_pipe

if [ -f /etc/login.defs ] && command -v awk &> /dev/null
then
    start_uid=$(id -u)
    min_uid=$(grep "^UID_MIN" /etc/login.defs | awk '{print $2}')
fi

if [ "$USER" = "root" -o "$UID" = "0" -o "start_uid" = "0" ]
then
    echo "WARNING: program should not be run as superuser" 1>&2
    exit 1
elif [ ! -z "$start_uid" -a ! -z "$min_uid" -a "$start_uid" -lt "$min_uid" ]
then
    echo "WARNING: program can only be run with user permissions" 1>&2
    exit 1
elif command -v pulseaudio &> /dev/null
then
    echo "found pulseaudio (${USER})"
    if pulseaudio --check
    then
        echo "restarting pulseaudio (${USER}).."
        pulseaudio -k
    else
        echo "starting pulseaudio (${USER}).."
        pulseaudio --start
    fi
elif command -v pipewire &> /dev/null
then
    echo "found pipewire (${USER})"
    echo "restarting pipewire and pipewire-pulse (${USER}).."
    systemctl --user restart pipewire pipewire-pulse
    check_pw_defaults
else
    echo "WARNING: neither pulseaudio nor pipewire (${USER}) were found" 1>&2
    exit 1
fi

display_manager="$(cat /etc/X11/default-display-manager | rev | cut -d'/' -f1 | rev)"
echo "$display_manager display manager has been detected"

unit=tera-record.service

if [ "$display_manager" = "fly-dm" ]; then
  # example: fly-dm
  # graphical-session.target работает бесконечно, независимо от входов и выходов пользователя [WP-5718]
  sleep 2147483647 &
  trap "exit_hook $! $unit $file_pipe" SIGINT SIGTERM
  systemctl --user start $unit && rc=$? || rc=$?
  if [ $rc -eq 0 ]; then
    wait
    echo "$unit has stopped working"
    exit 0
  fi
  # ...работа скрипта не будет завершена
  # в gdm3 это приводит к зависанию запуска .desktop ярлыков
else
  # example: gdm3
  # graphical-session.target запускается при каждом login-е пользователя и останавливается при logout-е [WP-5718]
  systemctl --user start $unit && rc=$? || rc=$?
fi

if [ $rc -ne 0 ]; then
  echo "WARNING: $unit did not start" 1>&2
fi
exit $rc
