#!/bin/bash

export MESSAGE=""

print_list() {
    pactl list sinks | awk '
    function rofi_set(prop, val) {
        print "\0"prop"\x1f"val
    }
    BEGIN {
        have_sink = 0
        i = 0
        "pactl get-default-sink" | getline active_sink
        list=""
        active_line=-1
    };
    /^Sink/ {
        new=mute" "name" ("volume")\0info\x1f"sink
        if (have_sink == active_line) {
            list=new"\n"list
        } else if (have_sink > 0) {
            list=list"\n"new
        }
        sink=substr($2,2);
        have_sink++

    };
    /Description/ {
        $1 = "" ;
        name = substr($0,2);
    };
    /Mute/ {
        if ( $2 == "yes") {
            mute="(M)"
        } else {
            mute=""
        }
    }
    /Volume/ && ! /Base Volume/ {
        if ( $5 == $12) {
            volume=$5
        } else {
            volume=$5"|"$12
        }
    }

    /Name/ && $2 == active_sink {
        active_line=have_sink   
    }
    END {
        new=mute" "name" ("volume")\0info\x1f"sink
        if (have_sink == active_line) {
            list=new"\n"list
        } else if (have_sink > 0) {
            list=list"\n"new
        }
        rofi_set("prompt", "Default sink")
        rofi_set("message", ENVIRON["MESSAGE"])
        rofi_set("use-hot-keys","true")
        rofi_set("active", "0")
        sub(/\n+/, "\n", list)
        print list
    }'
}

case "$ROFI_RETV" in
    0) : ;;
    1) pactl set-default-sink "$ROFI_INFO" ; exit 0 ;;
    10) pactl set-sink-volume "$ROFI_INFO" -10% ;;
    11) pactl set-sink-volume "$ROFI_INFO" +10% ;;
    12) pactl set-sink-mute "$ROFI_INFO" toggle ;;
    *) export MESSAGE="unknown action" ;;
esac

print_list
