#!/usr/bin/env fish

set -l sed 's/^.* ([[:digit:]]*)\. .*$/\1/'
set -l awk 'BEGIN { A=0; S=0; } /^Audio/ { A=1; } /Sinks/ { S=1; } /Sources/ { S=0; } /^Video/ { A=0; } { if (A==1 && S==1 && / [[:digit:]]*\./)  { print; } }'

set -l lines (wpctl status | awk $awk)
set -l len (count $lines)

set -l current
set -l sinks

for i in (seq 1 $len)
  set -l sink (echo $lines[$i] | sed -E $sed)
  set -a sinks $sink

  if string match -qr '\*' $lines[$i]
    set current $sink
  end

end

set -l len (count $sinks)
set -l index

for i in (seq 1 $len)
  if [ $sinks[$i] = $current ]
    if [ $argv[1] = '-f' ]
      if [ $i = $len ]
        set index 1
      else
        set index (math $i + 1)
      end
    else if [ $argv[1] = '-b' ]
      if [ $i = 1 ]
        set index $len
      else
        set index (math $i - 1)
      end
    else
      exit 1
    end
    break
  end
end

wpctl set-default $sinks[$index]
