#!/bin/sh
# $Id: battery-charge-threshold,v 1.3 2019/06/14 22:40:34 friedman Exp $

bat_devs()
{
    for bat in /sys/class/power_supply/BAT* ; do
        test -d $bat || continue
        echo ${bat##*/}
    done
}

read_thresh()
{
    local bat=/sys/class/power_supply/$1
    if ! [ -d $bat ]; then
        echo "$1: no such device." 1>&2
        return 1
    fi

    read cur_start < $bat/charge_start_threshold || return $?
    read cur_stop  < $bat/charge_stop_threshold  || return $?
}

write_thresh()
{
    local bat=/sys/class/power_supply/$1
    if ! [ -d $bat ]; then
        echo "$1: no such device." 1>&2
        return 1
    fi

    read_thresh $1

    case $new_start in '' | - ) new_start=$cur_start ;; esac
    case $new_stop  in '' | - ) new_stop=$cur_stop   ;; esac

    if [ $new_start -gt $new_stop ]; then
        eval new_start=$new_stop new_stop=$new_start
    fi

    if [ $new_start -gt $cur_stop ]; then
        echo -n $new_stop  > $bat/charge_stop_threshold  || return $?
        echo -n $new_start > $bat/charge_start_threshold || return $?
    else
        echo -n $new_start > $bat/charge_start_threshold || return $?
        echo -n $new_stop  > $bat/charge_stop_threshold  || return $?
    fi
}

print_thresh()
{
    case $# in
        0 ) echo "No batteries present" 1>&2
            return 1 ;;
    esac

    for bat in "$@"; do
        if read_thresh $bat; then
            printf "%s: %02d %02d\n" $bat $cur_start $cur_stop
        fi
    done
}

main()
{
    case $# in
        0 ) print_thresh `bat_devs`
            return $? ;;
        1 ) case $1 in
                [0-9]* ) usage ;;
                *      ) print_thresh $1
                         return $? ;;
            esac ;;
    esac

    case $1:$2 in
        [0-9]*: | [0-9]*:- | :[0-9]* | -:[0-9]* | [0-9]*:[0-9]* )
            new_start=$1 new_stop=$2
            shift 2

            case $# in 0 ) set : `bat_devs`; shift ;; esac
            case $# in 0 ) echo "No batteries present." 1>&2; return 1 ;; esac

            for bat in "$@"; do
                write_thresh $bat
            done
            return $?
    esac

    print_thresh "$@"
}

main "$@"

# eof
