#!/bin/sh

VOLUME_FILE=/etc/current_volume

# Check args
if [ ${#} -ne 1 ]; then
    echo "Usage: $(basename ${0}) new_volume_percentage"
    exit 1
fi

# Check value's range
if [ ${1} -gt 100 ]; then
    echo "Usage: Wrong volume percentage (${1}), must be between 0 and 100"
    exit 1
fi

# Scale new volume value between 0 and 63
volume_percent=${1}
vol_mini=16;
volume_scaled=$(echo "a = $volume_percent * (63 - $vol_mini) / 100 + $vol_mini + 0.5; scale = 0; a / 1" | bc -l)
echo $volume_scaled

# Get current value
current_volume=$(volume_get)

# Turn on/off audio amplifier if necessary
if [ ${current_volume} -eq 0 -a ${volume_percent} -ne 0 ]; then
    start_audio_amp 1
elif [ ${current_volume} -ne 0 -a ${volume_percent} -eq 0 ]; then
    start_audio_amp 0
fi

# Set new volume
amixer -q sset 'Headphone' ${volume_scaled} unmute

# Change new volume value in volume file
if [ ${?} -eq 0 ]; then
    rw
    echo ${volume_percent} > ${VOLUME_FILE}
    ro
fi
exit 0
