#!/bin/bash
#
# SwapImpedance 1.0.20150702
#   Script for switching impedance for Asus Xonar Essence XTS
#   Useful for desktop icon (shortcut to switch between impedances).
#   Made by Ole-Henrik Jakobsen CC BY-SA.
#
# Usage: ./swapimp
#
# Requirements: alsa (aplay/amixer), zenity

DEVICE=`aplay -l | grep "Xonar STX" | grep "Multichannel" | sed 's/card //' | cut -b 1`

IMP_CURRENT=`amixer -c $DEVICE sget 'Headphones Impedance',0 | grep Item0 | sed "s/  Item0: //" | sed "s/'/\"/g"`
IFS=$'\n' IMP_AVAILABLE=(`amixer -c $DEVICE sget 'Headphones Impedance',0 | grep Items | sed "s/  Items: //" | sed "s/' '/\n/g" | sed "s/'//g"`)
#IFS=$'\n' IMP_AVAILABLE=(`amixer -c $DEVICE sget 'Headphones Impedance',0 | grep Items | sed "s/  Items: //" | sed "s/' '/\"\n\"/g" | sed "s/'/\"/g" | sed "s/\"/false \"/" | sed "s/false $IMP_CURRENT/true $IMP_CURRENT/"`)
IFS=$'\n' IMP_STATE=(`amixer -c $DEVICE sget 'Headphones Impedance',0 | grep Items | sed "s/  Items: //" | sed "s/' '/\"\n\"/g" | sed "s/'/\"/g" | sed "s/\"/false \"/" | sed "s/false $IMP_CURRENT/true/" | cut -f1 -d" "`)

echo "Current impedance: $IMP_CURRENT. Available impedances: "

IMPEDANCE=`zenity --list --title="Select impedance" --text="Select impedance matching headset specification" --column="" --column="Impedance" --radiolist --width="300" --height="200" \
${IMP_STATE[0]} ${IMP_AVAILABLE[0]} \
${IMP_STATE[1]} ${IMP_AVAILABLE[1]} \
${IMP_STATE[2]} ${IMP_AVAILABLE[2]} \
${IMP_STATE[3]} ${IMP_AVAILABLE[3]}`

echo $IMPEDANCE

amixer -c $DEVICE sset 'Headphones Impedance',0 $IMPEDANCE