#!/bin/sh

set -eu

first_mixer_control() {
  amixer scontrols 2>/dev/null |
    sed -n "s/^Simple mixer control '\\([^']*\\)'.*/\\1/p" |
    sed -n '1p'
}

control=
for candidate in Master Speaker PCM Headphone; do
  if amixer sget "${candidate}" >/dev/null 2>&1; then
    control=${candidate}
    break
  fi
done

if [ -z "${control}" ]; then
  control=$(first_mixer_control)
fi

if [ -z "${control}" ]; then
  echo "No ALSA mixer control was found." >&2
  exit 1
fi

case "${1:-show}" in
  up)
    amixer -M sset "${control}" 5%+ unmute
    ;;
  down)
    amixer -M sset "${control}" 5%-
    ;;
  mute)
    amixer sset "${control}" toggle
    ;;
  show)
    amixer -M sget "${control}"
    ;;
  *)
    case "$1" in
      *[!0-9]*|"")
        echo "usage: volume {0..100|up|down|mute|show}" >&2
        exit 2
        ;;
    esac
    if [ "$1" -gt 100 ]; then
      echo "volume must be between 0 and 100" >&2
      exit 2
    fi
    amixer -M sset "${control}" "$1%" unmute
    ;;
esac
