#!/usr/bin/env bash
#
# Written by Ron Record <rr@ronrecord.com> December, 2022
#
# roon_fade - control Roon fading in specified zone or zone grouping
#
# Usage: roon_fade [-i] [-l] [-R] [-V] [-t duration] [-uh]
#                  [-y] [-z zone] on|off|now"
#
# shellcheck disable=SC1090,SC2220,SC2207,SC2009,SC2059

ROON=/usr/local/Roon
ROONETC=${ROON}/etc
ROONFADE=${ROONETC}/roon_faded
ROONCONF=${ROONETC}/pyroonconf
FADECONF=${ROONETC}/fadeconf
POS_INT='^[1-9][0-9]*(,[1-9][0-9]*)*$'
FADE_ZONE=
LOG=
BOLD=$(tput bold 2>/dev/null)
NORM=$(tput sgr0 2>/dev/null)

# Get the zone and fade settings
init_conf() {
  if [ -f ${ROONCONF} ]
  then
    . ${ROONCONF}
  else
    DEFZONE=$(grep ^DefaultZone ${ROONETC}/roon_api.ini | \
        awk -F '=' ' { print $2 } ')
    ${ROON}/bin/set_zone "${DEFZONE}"
    . ${ROONCONF}
  fi
  if [ -f ${FADECONF} ]
  then
    . ${FADECONF}
  else
    if [ "${FADE_ZONE}" ]
    then
      echo "FADE_ZONE=\"${FADE_ZONE}\"" > ${FADECONF}
    else
      echo "FADE_ZONE=\"${ROON_ZONE}\"" > ${FADECONF}
    fi
    if [ "${FADE_DURATION}" ]
    then
      echo "FADE_DURATION=${FADE_DURATION}" >> ${FADECONF}
    else
      echo "FADE_DURATION=30" >> ${FADECONF}
    fi
    if [ "${FADE_NOW}" ]
    then
      echo "FADE_NOW=${FADE_NOW}" >> ${FADECONF}
    else
      echo "FADE_NOW=false" >> ${FADECONF}
    fi
    if [ "${FADE_DISABLED}" ]
    then
      echo "FADE_DISABLED=${FADE_DISABLED}" >> ${FADECONF}
    else
      echo "FADE_DISABLED=false" >> ${FADECONF}
    fi
    if [ "${ROON_FADE}" ]
    then
      echo "ROON_FADE=${ROON_FADE}" >> ${FADECONF}
    else
      echo "ROON_FADE=false" >> ${FADECONF}
    fi
    . ${FADECONF}
  fi
}

start_daemon() {
    ps -ef | grep ${ROONFADE} | grep -v grep > /dev/null && {
      if [ "${proceed}" ] || [ "$1" == "-y" ]
      then
        stop_daemon
        init_conf
      else
        printf "\n%s appears to be running." "${ROONFADE}"
        printf "\nOnly one instance of 'roon_faded' is currently supported."
        printf "\nThe current process can be exited with 'roon_fade off'"
        printf "\nor by answering 'y' below.\n\n"
        while true
        do
          read -r -p "Exit 'roon_faded' and start a new one ? (y/n) " yn
          case $yn in
            [Yy]* )
                  stop_daemon
                  init_conf
                  break
                  ;;
            [Nn]* )
                  printf "\nRoon fading daemon startup aborted."
                  printf "\nExiting.\n\n"
                  exit 1
                  ;;
                * ) echo "Please answer yes or no."
                  ;;
          esac
        done
      fi
    }
    if [ -x ${ROONFADE} ]
    then
        [ "${ROON_FADE}" = true ] || set_roon_fade on
        [ "${FADE_DURATION}" ] || set_fade_time 30
        set_fade_zone
        echo "Starting Roon fade daemon ${ROONFADE}"
        [ "${LOG}" ] && echo "Logging in ${ROONETC}/faded_log.txt"
        ${ROONFADE} ${LOG} -z "${FADE_ZONE}" > /dev/null 2>&1 &
    else
        echo "Roon fade daemon ${ROONFADE} not found or not executable"
    fi
}

stop_daemon() {
    set_roon_fade off
    printf "\nRoon fade disabled in %s" "${FADECONF}"
    printf "\nWaiting for %s to exit ..." "${ROONFADE}"
    if [ "${proceed}" ]
    then
      elapsed=10
    else
      elapsed=0
    fi
    while true
    do
      running=
      ps -ef | grep ${ROONFADE} | grep -v grep > /dev/null && {
        running=1
        printf "."
        sleep 2
        elapsed=$((elapsed + 2))
      }
      [ "${running}" ] || {
        printf " done\n"
        break
      }
      [ ${elapsed} -gt 10 ] && {
        faded_pid=$(ps -ef | grep roon_faded | \
                            grep -v grep | awk ' { print $2 } ')
        [ "${faded_pid}" ] && kill "${faded_pid}"
      }
    done
}

save_vols() {
    grep -v ZONES= ${FADECONF} > /tmp/ftmp$$
    grep -v OUTSTEP= /tmp/ftmp$$ > /tmp/otmp$$
    grep -v CURVOL= /tmp/otmp$$ > /tmp/fade$$
    rm -f /tmp/ftmp$$ /tmp/otmp$$
    printf "ZONES=( " >> /tmp/fade$$
    for z in ${!ZONES[@]}
    do
      printf "\"${ZONES[$z]}\" " >> /tmp/fade$$
    done
    printf ")\n" >> /tmp/fade$$

    printf "OUTSTEP=( " >> /tmp/fade$$
    for s in ${OUTSTEP[@]}
    do
      printf "$s " >> /tmp/fade$$
    done
    printf ")\n" >> /tmp/fade$$

    printf "CURVOL=( " >> /tmp/fade$$
    for v in ${CURVOL[@]}
    do
      printf "%d " "$v" >> /tmp/fade$$
    done
    printf ")\n" >> /tmp/fade$$
    cp /tmp/fade$$ ${FADECONF}
    rm -f /tmp/fade$$
}

show_status() {
  if [ "${FADE_ZONE}" ]
  then
    if [ "${have_rich}" ]
    then
      rich "Configured Roon fading zone: [bold magenta]${FADE_ZONE}[/]" --print
    else
      printf "\nConfigured Roon fading zone: ${BOLD}${FADE_ZONE}${NORM}"
    fi
  else
    printf "\nNo Roon fading zone is configured"
  fi
  if [ "${FADE_DURATION}" ]
  then
    if [ "${have_rich}" ]
    then
      rich "Fade duration set to: [bold magenta]${FADE_DURATION}[/]" --print
    else
      printf "\nFade duration set to: ${BOLD}${FADE_DURATION}${NORM}"
    fi
  else
    printf "\nNo Fade duration is configured"
  fi
  if [ "${ROON_FADE}" = true ]
  then
    if [ "${FADE_ZONE}" ]
    then
      if [ "${have_rich}" ]
      then
        rich "Roon volume fading is: [bold italic]Currently [green]enabled[/] in zone[/] [bold magenta]${FADE_ZONE}[/]" --print
      else
        printf "\nRoon volume fading is: ${BOLD}Currently enabled in zone ${FADE_ZONE}${NORM}"
      fi
    else
      if [ "${have_rich}" ]
      then
        rich "Roon volume fading is: [bold italic]Currently [green]enabled[/][/]" --print
      else
        printf "\nRoon volume fading is: ${BOLD}Currently enabled${NORM}"
      fi
    fi
  else
    if [ "${have_rich}" ]
    then
      rich "Roon volume fading is: [bold italic]Currently [yellow]disabled[/][/]" --print
    else
      printf "\nRoon volume fading is: ${BOLD}Currently disabled${NORM}"
    fi
  fi
  if [ "${FADE_NOW}" = true ]
  then
    if [ "${have_rich}" ]
    then
      rich "Volume levels are: [bold italic yellow]Currently faded[/]" --print
    else
      printf "\nVolume levels are: ${BOLD}Currently faded${NORM}\n\n"
    fi
  else
    if [ "${have_rich}" ]
    then
      rich "Volume levels are: [bold italic green]Not currently faded[/]" --print
    else
      printf "\nVolume levels are: ${BOLD}Not currently faded${NORM}\n\n"
    fi
  fi
}

usage() {
  if [ "${have_rich}" ]
  then
    rich "[bold]Usage:[/] [bold italic green]roon_fade[/] \[[cyan]-i[/]] \[[cyan]-l[/]] \[[cyan]-R[/]] \[[cyan]-V[/]] \[[cyan]-t[/] [yellow]duration[/]] \[[cyan]-uh[/]] \[[cyan]-y[/]] \[[cyan]-z[/] [yellow]zone[/]] [bold italic green]on|off|now[/]" --print
    rich "[bold]Where:[/]" --print
    rich "  [cyan]-i[/] indicates [italic]interactive mode[/] and displays a menu of options" --print
    rich "  [cyan]-l[/] enables [italic]logging[/]" --print
    rich "  [cyan]-R[/] [italic]restores[/] faded or modified volume to original levels" --print
    rich "  [cyan]-V[/] updates fading restore volume to [italic]current volume levels[/]" --print
    rich "      (use [bold italic green]roon_fade -V[/] after manually adjusting volume)" --print
    rich "  [cyan]-t[/] [yellow]duration[/] sets the [italic]fade duration[/] (default: [yellow]30[/])" --print
    rich "  [cyan]-y[/] indicates do not prompt, assume the answer is [italic]yes[/] and proceed" --print
    rich "  [cyan]-z[/] [yellow]zone[/] sets the [italic]Roon zone[/] in which to fade" --print
    rich "      (if no zone is specified, the default zone is used)" --print
    printf "\n"
    rich "An argument of [bold italic green]on[/] enables end of track fading, [bold italic green]off[/] disables track fading" --print
    rich "An argument of [bold italic green]now[/] toggles immediate fading of volume" --print
    rich "An argument of [cyan]-u[/] or [cyan]-h[/] displays this usage message" --print
    rich "Without arguments, status and a usage message is displayed" --print
    printf "\n"
  else
    printf "\nUsage: roon_fade [-i] [-l] [-R] [-V] [-t duration] [-uh] [-y] [-z zone] on|off|now"
    printf "\nWhere:"
    printf "\n\t-i indicates interactive mode and displays a menu of options"
    printf "\n\t-l enables logging"
    printf "\n\t-R restores faded or modified volume to original levels"
    printf "\n\t-V updates fading restore volume to current volume levels"
    printf "\n\t\t(use 'roon_fade -V' after manually adjusting volume)"
    printf "\n\t-t 'duration' sets the fade duration (default: 30)"
    printf "\n\t-y indicates do not prompt, assume the answer is 'yes' and proceed"
    printf "\n\t-z 'zone' sets the Roon zone in which to fade"
    printf "\n\t\tIf no zone is specified, the default zone is used\n"
    printf "\nAn argument of 'on' enables end of track fading, 'off' disables track fading"
    printf "\nAn argument of 'now' toggles immediate fading of volume"
    printf "\nAn argument of '-u' or '-h' displays this usage message"
    printf "\nWithout arguments, status and a usage message is displayed\n"
  fi
  show_status
  exit 1
}

init_vols() {
    FADE_DRTN=30
    [ "${FADE_DURATION}" ] && {
      FADE_DRTN=${FADE_DURATION}
    }
    ZONES=()
    CURVOL=()
    OUTSTEP=()
    finish=()
    minvol=()
    outdiv=$((FADE_DRTN / 4))
    while read voline
    do
      zone=$(echo "${voline}" | awk -F ':' ' { print $1 } ' | \
                               sed -e 's/^ *//' -e 's/ *$//')
      ZONES+=( "${zone}" )
      volume=$(echo "${voline}" | awk -F ':' ' { print $2 } ' | \
                                 awk -F ',' ' { print $1 } ' | \
                                 awk -F '=' ' { print $2 } ' | \
                                 sed -e 's/^ *//' -e 's/ *$//')
      CURVOL+=( ${volume} )
      finish+=( 0 )
      minimum=$(echo "${voline}" | awk -F ':' ' { print $2 } ' | \
                                  awk -F ',' ' { print $2 } ' | \
                                  awk -F '=' ' { print $2 } ' | \
                                  sed -e 's/^ *//' -e 's/ *$//')
      minvol+=( ${minimum} )
      diff=$((volume - minimum))
      outstep=$((diff / outdiv))
      OUTSTEP+=( ${outstep} )
    done < <(get_zone_volume -g -z "${FADE_ZONE}")
    save_vols
}

set_disabled() {
    grep -v FADE_DISABLED ${FADECONF} > /tmp/fade$$
    if [ "$1" == "on" ]
    then
      echo "FADE_DISABLED=true" >> /tmp/fade$$
    else
      echo "FADE_DISABLED=false" >> /tmp/fade$$
    fi
    cp /tmp/fade$$ ${FADECONF}
    rm -f /tmp/fade$$
}

set_now() {
    grep -v FADE_NOW ${FADECONF} > /tmp/fade$$
    if [ "$1" == "on" ]
    then
      echo "FADE_NOW=true" >> /tmp/fade$$
    else
      echo "FADE_NOW=false" >> /tmp/fade$$
    fi
    cp /tmp/fade$$ ${FADECONF}
    rm -f /tmp/fade$$
}

set_fade_init() {
    grep -v FADE_INIT ${FADECONF} > /tmp/fade$$
    echo "FADE_INIT=1" >> /tmp/fade$$
    cp /tmp/fade$$ ${FADECONF}
    rm -f /tmp/fade$$
}

set_fade_zone() {
    grep -v FADE_ZONE ${FADECONF} > /tmp/fade$$
    echo "FADE_ZONE=\"${FADE_ZONE}\"" >> /tmp/fade$$
    cp /tmp/fade$$ ${FADECONF}
    rm -f /tmp/fade$$
}

set_roon_fade() {
    grep -v ROON_FADE ${FADECONF} > /tmp/fade$$
    if [ "$1" == "on" ]
    then
      echo "ROON_FADE=true" >> /tmp/fade$$
    else
      echo "ROON_FADE=false" >> /tmp/fade$$
    fi
    cp /tmp/fade$$ ${FADECONF}
    rm -f /tmp/fade$$
}

set_fade_time() {
    grep -v FADE_DURATION ${FADECONF} > /tmp/fade$$
    echo "FADE_DURATION=$1" >> /tmp/fade$$
    cp /tmp/fade$$ ${FADECONF}
    rm -f /tmp/fade$$
}

fade_in() {
    init_conf
    for f in ${!ZONES[@]}
    do
      finish[$f]=0
    done
    echo "Restoring volume levels in ${FADE_ZONE} zone"
    while true
    do
      for z in ${!ZONES[@]}
      do
        cvol=${CURVOL[$z]}
        zone=${ZONES[$z]}
        step=${OUTSTEP[$z]}
        zvol=$(get_zone_volume -n -z "${zone}")
        boom=$((cvol - zvol))
        if [ ${boom} -le ${step} ]
        then
          [ ${finish[$z]} -eq 1 ] || {
            set_volume -v "${cvol}" -z "${zone}"
            finish[$z]=1
          }
        else
          set_volume -r -v "${step}" -z "${zone}"
        fi
      done
      faded=1
      for fin in ${finish[@]}
      do
          [ ${fin} -eq 0 ] && {
              faded=
              break
          }
      done
      [ "${faded}" ] && break
    done
}

fade_out() {
    init_vols
    echo "Fading volume levels in ${FADE_ZONE} zone"
    while true
    do
      for z in ${!ZONES[@]}
      do
        step=${OUTSTEP[$z]}
        zone=${ZONES[$z]}
        mvol=${minvol[$z]}
        zvol=$(get_zone_volume -n -z "${zone}")
        if [ ${zvol} -le ${mvol} ]
        then
          [ ${finish[$z]} -eq 1 ] || finish[$z]=1
        else
          set_volume -r -v "-${step}" -z "${zone}"
        fi
      done
      faded=1
      for fin in ${finish[@]}
      do
        [ ${fin} -eq 0 ] && {
          faded=
          break
        }
      done
      [ "${faded}" ] && {
        roon -c "pause" -z "${FADE_ZONE}"
        break
      }
    done
}

fade_now() {
    if [ "${FADE_NOW}" = true ]
    then
        roon -c "play" -z "${FADE_ZONE}"
        sleep 1
        set_now off
        fade_in
        [ "${FADE_DISABLED}" = true ] && {
            start_daemon -y
            set_disabled off
        }
    else
        ps -ef | grep ${ROONFADE} | grep -v grep > /dev/null && {
            # Disable the fading daemon in this zone
            stop_daemon
            set_disabled on
        }
        set_now on
        fade_out
    fi
}

select_fade_duration() {
  duration_options=()
  dur=5
  while [ ${dur} -le 100 ]
  do
    duration_options+=("${dur}")
    dur=$((dur + 5))
  done
  duration_options+=("Main Fade Menu [m]" "Main Roon Menu [M]" "Quit           [q]")
  while true
  do
    tput clear
    [ "${have_rich}" ] && {
      rich "[bold][cyan]RoonCommandLine Fade Duration[/cyan][/bold]" -p -a rounded -c -C
    }
    PS3="${BOLD}Please enter the fade duration you desire (numeric or text): ${NORM}"
    select opt in "${duration_options[@]}"
    do
        case "$opt,$REPLY" in
            "Main Fade Menu"*,*|*,"Main Fade Menu"* | "m",* | *,"m")
                show_menu
                break 2
                ;;
            "Main Roon Menu"*,*|*,"Main Roon Menu"* | "M",* | *,"M")
                exec roon -m
                break 2
                ;;
            "Quit"*,*|*,"Quit"*|"quit"*,*|*,"quit"* | "q",* | *,"q")
                printf "\nExiting\n"
                exit 0
                ;;
            *,*)
                if [[ " ${duration_options[*]} " =~ " ${opt} " ]]
                then
                  echo "${BOLD}Setting fade duration to: ${opt}${NORM}"
                  FADE_DURATION="${opt}"
                  set_fade_time ${FADE_DURATION}
                  status=$?
                  [ ${status} -eq 0 ] || {
                    echo "Unable to set fade duration to $opt"
                  }
                  break 2
                else
                  printf "\n\nInvalid option: ${opt}"
                  printf "\n\tPlease enter either the exact text or numeric designation"
                  printf "\n\tfor one of the listed options below.\n\n"
                  break
                fi
                ;;
        esac
    done
  done
}

select_fade_zone() {
  ${IFS+"false"} && unset oldifs || oldifs="$IFS"
  IFS=$'\n'
  zones=$(${ROON}/bin/get_zones | sed -e 's/\, /\,/g')
  zone_options=( $( echo "${zones}" | \
    awk -F "," ' { for(i=1;i<=NF;i++) printf "%s\n",$i }' ) )
  ${oldifs+"false"} && unset IFS || IFS="$oldifs"
  zone_options+=("Main Fade Menu [m]" "Main Roon Menu [M]" "Quit           [q]")
  while true
  do
    tput clear
    [ "${have_rich}" ] && {
      rich "[bold][cyan]RoonCommandLine Fade Zone[/cyan][/bold]" -p -a rounded -c -C
    }
    PS3="${BOLD}Please enter the Roon zone you wish to fade (numeric or text): ${NORM}"
    select opt in "${zone_options[@]}"
    do
        case "$opt,$REPLY" in
            "Main Fade Menu"*,*|*,"Main Fade Menu"* | "m",* | *,"m")
                show_menu
                break 2
                ;;
            "Main Roon Menu"*,*|*,"Main Roon Menu"* | "M",* | *,"M")
                exec roon -m
                break 2
                ;;
            "Quit"*,*|*,"Quit"*|"quit"*,*|*,"quit"* | "q",* | *,"q")
                printf "\nExiting\n"
                exit 0
                ;;
            *,*)
                if [[ " ${zone_options[*]} " =~ " ${opt} " ]]
                then
                  if [ "${FADE_ZONE}" == "${opt}" ]
                  then
                    echo "Fade zone already set to: ${BOLD}${opt}${NORM}"
                  else
                    [ "${FADE_NOW}" = true ] && {
                      # Unfade the current zone before switching fade zones
                      set_now off
                      fade_in
                      [ "${FADE_DISABLED}" = true ] && {
                          start_daemon -y
                          set_disabled off
                      }
                    }
                    echo "Setting fading zone to: ${BOLD}${opt}${NORM}"
                    FADE_ZONE="${opt}"
                    set_fade_zone
                    status=$?
                    [ ${status} -eq 0 ] || {
                      echo "Unable to set fade zone for zone = $opt"
                    }
                    init_vols
                    # Tell roon_faded, if running, to re-initialize zone values
                    [ "${ROON_FADE}" = true ] && set_fade_init
                  fi
                  break 2
                else
                  printf "\n\nInvalid option: ${opt}"
                  printf "\n\tPlease enter either the exact text or numeric designation"
                  printf "\n\tfor one of the listed options below.\n\n"
                  break
                fi
                ;;
        esac
    done
  done
}

show_menu() {
  while true
  do
    tput clear
    [ "${have_rich}" ] && {
      rich "[bold][cyan]RoonCommandLine Fade Menu[/cyan][/bold]" -p -a rounded -c -C
    }
    init_conf
    remline=$(get_zone_remaining -z "${FADE_ZONE}")
    if echo "${remline}" | grep , > /dev/null; then
      state=$(echo "${remline}" | awk -F ',' ' { print $2 } ' | \
                                  awk -F '=' ' { print $2 } ' | \
                                  sed -e 's/^ *//' -e 's/ *$//')
    else
      state=$(echo "${remline}" | awk -F ':' ' { print $2 } ' | \
                                  awk -F '=' ' { print $2 } ' | \
                                  sed -e 's/^ *//' -e 's/ *$//')
    fi
    echo ""
    if [ "${state}" == "playing" ]
    then
      echo "Audio in zone ${FADE_ZONE} is: ${BOLD}Playing${NORM}"
    else
      echo "Audio in zone ${FADE_ZONE} is: ${BOLD}Not playing${NORM}"
    fi
    show_status
    echo ""
    PS3="${BOLD}Please enter your Roon fading choice (numeric or text): ${NORM}"
    options=()
    if [ "${FADE_NOW}" = true ]
    then
      options+=("Restore Volume       [r]")
    else
      options+=("Fade Now             [f]")
    fi
    if [ "${ROON_FADE}" = true ]
    then
      options+=("Disable Fade Daemon  [d]")
    else
      options+=("Enable Fade Daemon   [e]")
    fi
    if [ "${state}" == "playing" ]
    then
      options+=("Pause in Fading Zone [P]")
    else
      options+=("Play in Fading Zone  [p]")
    fi
    options+=("Set Fade Duration    [s]" "Select Fade Zone     [z]" "Toggle Mute          [t]")
    options+=("Main Roon Menu       [m]" "Quit                 [q]")
    select opt in "${options[@]}"
    do
        case "$opt,$REPLY" in
            "Restore Volume"*,*|*,"Restore Volume"*|"Fade Now"*,*|*,"Fade Now"* | "r",* | *,"r" | "f",* | *,"f")
                fade_now
                break
                ;;
            "Disable Fade Daemon"*,*|*,"Disable Fade Daemon"* | "d",* | *,"d")
                stop_daemon
                break
                ;;
            "Enable Fade Daemon"*,*|*,"Enable Fade Daemon"* | "e",* | *,"e")
                start_daemon -y
                sleep 2
                break
                ;;
            "Pause"*,*|*,"Pause"* | "P",* | *,"P")
                roon -c pause -z "${FADE_ZONE}"
                sleep 2
                break
                ;;
            "Play"*,*|*,"Play"* | "p",* | *,"p")
                if [ "${FADE_NOW}" = true ]
                then
                  fade_now
                  sleep 1
                else
                  roon -c play -z "${FADE_ZONE}"
                  sleep 2
                fi
                break
                ;;
            "Toggle Mute"*,*|*,"Toggle Mute"* | "t",* | *,"t")
                roon -c mute -z "${FADE_ZONE}"
                break
                ;;
            "Set Fade Duration"*,*|*,"Set Fade Duration"* | "s",* | *,"s")
                init_conf
                if [ "${FADE_DURATION}" ]
                then
                    echo "Current Fade Duration is ${FADE_DURATION}"
                else
                    echo "No Fade Duration is set in ${FADECONF}"
                fi
                select_fade_duration
                break
                ;;
            "Select Fade Zone"*,*|*,"Select Fade Zone"* | "z",* | *,"z")
                init_conf
                if [ "${FADE_ZONE}" ]
                then
                    echo "Current Roon Fade Zone is ${FADE_ZONE}"
                else
                    echo "No default Roon Fade Zone is set in ${FADECONF}"
                fi
                select_fade_zone
                break
                ;;
            "Main Roon Menu"*,*|*,"Main Roon Menu"* | "m",* | *,"m")
                exec roon -m
                break
                ;;
            "Quit"*,*|*,"Quit"*|"quit"*,*|*,"quit"* | "q",* | *,"q")
                printf "\nExiting\n"
                exit 0
                ;;
        esac
    done
  done
}

# Use a Python virtual environment
[ -f ${ROON}/venv/bin/activate ] && source ${ROON}/venv/bin/activate
[[ ":$PATH:" == *":/usr/local/Roon/venv/bin:"* ]] || {
  export PATH=/usr/local/Roon/venv/bin:${PATH}
}

init_conf

fadetime=
fadeinit=
have_rich=$(type -p rich)
interact=
proceed=
restore=
# Parse the arguments to get the command and zone
while getopts "ilRt:Vyz:hu" flag; do
    case $flag in
        i)
            interact=1
            ;;
        l)
            LOG="-l"
            ;;
        R)
            ps -ef | grep ${ROONFADE} | grep -v grep > /dev/null && {
              echo "Restoring volume levels"
              grep -v RESTORE_VOLUME ${FADECONF} > /tmp/fade$$
              echo "RESTORE_VOLUME=1" >> /tmp/fade$$
              cp /tmp/fade$$ ${FADECONF}
              rm -f /tmp/fade$$
              restore=1
            }
            [ "${restore}" ] || {
              echo "${ROONFADE} does not appear to be running"
              echo "Volume levels must be restored manually"
            }
            ;;
        t)
            fadetime="$OPTARG"
            [ "${fadetime}" == "default" ] && fadetime=30
            if [[ ${fadetime} =~ ${POS_INT} ]]
            then
                if [ ${fadetime} -eq ${FADE_DURATION} ]
                then
                    echo "Fade duration already set to ${fadetime}"
                else
                    echo "Setting fade duration to ${fadetime}"
                    set_fade_time ${fadetime}
                fi
            else
                echo "${fadetime} is not a positive integer. Ignoring."
            fi
            ;;
        V)
            ps -ef | grep ${ROONFADE} | grep -v grep > /dev/null && {
              echo "Updating restored volume levels for fading"
              set_fade_init
              fadeinit=1
            }
            [ "${fadeinit}" ] || {
              echo "${ROONFADE} does not appear to be running"
              echo "Volume levels must be updated by stopping and restarting fade"
            }
            ;;
        y)
            proceed=1
            ;;
        z)
            FADE_ZONE="$OPTARG"
            ;;
        h|u)
            usage
            ;;
    esac
done
shift $(( OPTIND - 1 ))

[ "${FADE_ZONE}" ] || FADE_ZONE="${ROON_ZONE}"

if [ "$1" ]
then
    [ "$2" ] && {
      echo "Ignoring \"$2\" argument and any other following arguments."
      echo "Only one of 'on', 'off', or 'now' command line arguments are recognized."
    }
    argument=$(echo "$1" | tr '[:upper:]' '[:lower:]')
    if [ "${argument}" == "on" ]
    then
        start_daemon
    else
        if [ "${argument}" == "off" ]
        then
            [ "${ROON_FADE}" = true ] && stop_daemon
        else
            # For immediate fade we toggle the fade here
            if [ "${argument}" == "now" ]
            then
              fade_now
            else
                usage
            fi
        fi
    fi
else
    if [ "${interact}" ]
    then
      show_menu
    else
      [ "${fadeinit}" ] || [ "${restore}" ] || [ "${fadetime}" ] || usage
    fi
fi
exit 0
