#!/bin/sh
# samsung - Battery Plugin for Samsung laptops w/ samsung_laptop driver
#
# Copyright (c) 2023 Thomas Koch <linrunner at gmx.net> and others.
# SPDX-License-Identifier: GPL-2.0-or-later

# Needs: tlp-func-base, 35-tlp-func-batt, tlp-func-stat

# --- Hardware Detection

readonly BATDRV_SAMSUNG_MD=/sys/devices/platform/samsung

batdrv_is_samsung () {
    # check if kernel module loaded
    # rc: 0=Samsung, 1=other hardware
    [ -d $BATDRV_SAMSUNG_MD ]
}

# --- Plugin API functions

readonly BATDRV_SAMSUNG_BLE="${BATDRV_SAMSUNG_MD}/battery_life_extender"

batdrv_init () {
    # detect hardware and initialize driver
    # rc: 0=matching hardware detected/1=not detected/2=no batteries detected
    # retval: $_batdrv_plugin, $batdrv_kmod
    #
    # 1. check for vendor specific kernel api
    #    --> retval $_natacpi:
    #       0=thresholds/
    #       32=disabled/
    #       128=no kernel support/
    #       254=laptop not supported
    #
    # 2. determine method for
    #    reading battery data                   --> retval $_bm_read,
    #    reading/writing charging thresholds    --> retval $_bm_thresh,
    #    reading/writing force discharge        --> retval $_bm_dischg:
    #       none/natacpi
    #
    # 3. determine present batteries
    #    list of batteries (space separated)    --> retval $_batteries;
    #
    # 4. define battery life extender config, sysfile and default
    #    START/STOP_CHARGE_THRESH_ suffix       --> retval $_bt_cfg_bat,
    #    sysfile                                --> retval $_bf_stop,
    #    default                                --> retval $_bt_def_stop;

    _batdrv_plugin="samsung"
    _batdrv_kmod="samsung_laptop" # kernel module for natacpi

    # check plugin simulation override and denylist
    if [ -n "$X_BAT_PLUGIN_SIMULATE" ]; then
        if [ "$X_BAT_PLUGIN_SIMULATE" = "$_batdrv_plugin" ]; then
            echo_debug "bat" "batdrv_init.${_batdrv_plugin}.simulate"
        else
            echo_debug "bat" "batdrv_init.${_batdrv_plugin}.simulate_skip"
            return 1
        fi
    elif wordinlist "$_batdrv_plugin" "$X_BAT_PLUGIN_DENYLIST"; then
        echo_debug "bat" "batdrv_init.${_batdrv_plugin}.denylist"
        return 1
    else
        # check if hardware matches
        if ! batdrv_is_samsung; then
            echo_debug "bat" "batdrv_init.${_batdrv_plugin}.no_match"
            return 1
        fi
    fi

    # presume no features at all
    _natacpi=128
    # shellcheck disable=SC2034
    _bm_read="natacpi"
    _bm_thresh="none"
    # shellcheck disable=SC2034
    _bm_dischg="none"
    _batteries=""
    # shellcheck disable=SC2034
    _bt_cfg_bat="BAT0"
    _bf_stop=""
    _bt_def_stop=0

    # iterate batteries
    local bd bs
    for bd in "$ACPIBATDIR"/BAT[01]; do
        if [ "$(read_sysf "$bd/present")" = "1" ]; then
            # record detected batteries and directories
            bs=${bd##/*/}
            if [ -n "$_batteries" ]; then
                _batteries="$_batteries $bs"
            else
                _batteries="$bs"
            fi
        fi
    done

    # check for vendor specific kernel api
    if [ "$NATACPI_ENABLE" = "0" ]; then
        # natacpi disabled in configuration --> skip actual detection
        _natacpi=32
    elif [ -f "$BATDRV_SAMSUNG_BLE" ] && readable_sysf "$BATDRV_SAMSUNG_BLE"; then
        # sysfile exists and is actually readable
        _natacpi=0
        _bm_thresh="natacpi"
        _bf_stop="$BATDRV_SAMSUNG_BLE"
    elif [ "$X_BAT_PLUGIN_SIMULATE" = "$_batdrv_plugin" ]; then
        # simulate api
        _natacpi=0
        _bm_thresh="natacpi"
        _bf_stop="$BATDRV_SAMSUNG_BLE"
    else
        # nothing detected
        _natacpi=254
    fi

    # shellcheck disable=SC2034
    _batdrv_selected=$_batdrv_plugin
    echo_debug "bat" "batdrv_init.${_batdrv_plugin}: batteries=$_batteries; natacpi=$_natacpi; thresh=$_bm_thresh; bf_stop=$_bf_stop"
    return 0
}

batdrv_select_battery () {
    # determine battery acpidir
    # $1: BAT0/BAT1/DEF
    # # rc: 0=bat exists/1=bat non-existent
    # retval: $_bat_str:   BAT0/BAT1;
    #         $_bd_read:   directory with battery data sysfiles;
    # prerequisite: batdrv_init()

    # defaults
    _bat_str=""   # no bat
    _bd_read=""   # no directory

    # validate battery param
    local bs
    case $1 in
        DEF) # 1st battery is default
            _bat_str="${_batteries%% *}"
            ;;

        *)
            if wordinlist "$1" "$_batteries"; then
                _bat_str=$1
            else
                # battery not present --> quit
                echo_debug "bat" "batdrv.${_batdrv_plugin}.select_battery($1).not_present"
                return 1
            fi
            ;;
    esac

    # determine natacpi sysfiles
    _bd_read="$ACPIBATDIR/$_bat_str"

    echo_debug "bat" "batdrv.${_batdrv_plugin}.select_battery($1): bat_str=$_bat_str; bd_read=$_bd_read;"
    return 0
}

batdrv_read_threshold () {
    # read and print charge threshold (stop only)
    # global param: $_bf_stop
    # out: threshold 0/1/"" on error
    # rc: 0=ok/4=read error/255=no api
    # prerequisite: batdrv_init(), batdrv_select_battery()

    local out="" rc=0

    out="$X_THRESH_SIMULATE_STOP"
    if [ -n "$out" ]; then
        printf "%s" "$out"
        echo_debug "bat" "batdrv.${_batdrv_plugin}.read_threshold.simulate: bf_stop=$_bf_stop; out=$out; rc=$rc"
        return 0
    fi

    if [ "$_bm_thresh" = "natacpi" ]; then
        out=$(read_sysf "$_bf_stop") || rc=4
    else
        # no threshold api
        rc=255
    fi

    # "return" threshold
    if [ "$X_THRESH_SIMULATE_READERR" != "1" ]; then
        printf "%s" "$out"
    else
        rc=4
    fi

    echo_debug "bat" "batdrv.${_batdrv_plugin}.read_threshold: bf_stop=$_bf_stop; out=$out; rc=$rc"
    return $rc
}

batdrv_write_thresholds () {
    # write charge thresholds for a battery
    # use pre-determined method and sysfiles from global parms
    # $1: new start threshold -- unused dummy for plugin api compatibility
    # $2: new stop threshold 0/1/DEF(default)
    # $3: 0=quiet/1=output parameter errors/2=output progress and errors
    # $4: battery - non-empty string indicates thresholds stem from configuration
    # global param: $_bat_str, $_bf_stop
    # rc: 0=ok/
    #     1=not configured/
    #     2=threshold out of range or non-numeric/
    #     4=threshold read error/
    #     5=threshold write error
    # prerequisite: batdrv_init(), batdrv_select_battery()
    local new_stop=${2:-}
    local verb=${3:-0}
    local cfg_bat="$4"
    local old_stop

    # insert defaults
    [ "$new_stop" = "DEF" ] && new_stop=$_bt_def_stop

    # --- validate thresholds
    local rc

    if [ -n "$cfg_bat" ] && [ -z "$new_stop" ]; then
        # do nothing if unconfigured
        echo_debug "bat" "batdrv.${_batdrv_plugin}.write_thresholds($2, $3, $4).not_configured: bat=$_bat_str"
        return 1
    fi

    # stop: check for 3 digits max, ensure 0 or 1
    if ! is_uint "$new_stop" 3 || \
       ! is_within_bounds "$new_stop" 0 1; then
        # threshold out of range
        echo_debug "bat" "batdrv.${_batdrv_plugin}.write_thresholds($2, $3, $4).invalid_stop"
        case $verb in
            1)
                if [ -n "$cfg_bat" ]; then
                    echo_message "Error in configuration at STOP_CHARGE_THRESH_${cfg_bat}=\"${new_stop}\": life extender not specified or invalid (must be 0 or 1). Skipped."
                fi
                ;;

            2)
                if [ -n "$cfg_bat" ]; then
                    printf "Error in configuration at STOP_CHARGE_THRESH_%s=\"%s\": life extender not specified or invalid (must be 0 or 1). Aborted.\n" "$cfg_bat" "$new_stop" 1>&2
                else
                    printf "Error: life extender (%s) not specified or invalid (must be 0 or 1). Aborted.\n" "$new_stop" 1>&2
                fi
                ;;
        esac
        return 2
    fi

    # read active stop threshold value
    if ! old_stop=$(batdrv_read_threshold); then
        echo_debug "bat" "batdrv.${_batdrv_plugin}.write_thresholds($2, $3, $4).read_error"
        case $verb in
            1) echo_message "Error: could not read current life extender. Skipped." ;;
            2) printf "Error: could not read current life extender. Aborted.\n" 1>&2 ;;
        esac
        return 4
    fi

    # write new threshold
    if [ "$verb" = "2" ]; then
        printf "Setting temporary charge threshold for all batteries:\n"
    fi

    local rc=0
    if [ "$old_stop" != "$new_stop" ]; then
        # new threshold differs from effective one --> write it
        write_sysf "$new_stop" "$_bf_stop" || rc=5
        echo_debug "bat" "batdrv.${_batdrv_plugin}.write_thresholds($2, $3, $4).write: old=$old_stop; new=$new_stop; rc=$rc"
        case $verb in
            2)
                if [ $rc -eq 0 ]; then
                    printf "  life extender = %d\n" "$new_stop"
                else
                    printf "  life extender = %d (Error: write failed)\n" "$new_stop" 1>&2
                fi
                ;;
            1)
                if [ $rc -gt 0 ]; then
                    echo_message "Error: writing life extender failed."
                fi
                ;;
        esac
    else
        echo_debug "bat" "batdrv.${_batdrv_plugin}.write_thresholds($2, $3, $4).no_change: old=$old_stop; new=$new_stop"
        if [ "$verb" = "2" ]; then
                printf "  life extender = %d (no change)\n" "$new_stop"
        fi
    fi

    return $rc
}

batdrv_chargeonce () {
    # function not implemented for Samsung laptops
    echo_debug "bat" "batdrv.${_batdrv_plugin}.charge_once.not_implemented"
    return 255
}

batdrv_apply_configured_thresholds () {
    # apply configured battery life extender from configuration (concerns all batteries)
    # output parameter errors only

    batdrv_write_thresholds "DEF" "$STOP_CHARGE_THRESH_BAT0" 1 "BAT0"; rc=$?

    return 0
}

batdrv_read_force_discharge () {
    # function not implemented for Samsung laptops
    echo_debug "bat" "batdrv.${_batdrv_plugin}.read_force_discharge.not_implemented"
    return 255
}

batdrv_write_force_discharge () {
    # function not implemented for Samsung laptops
    echo_debug "bat" "batdrv.${_batdrv_plugin}.write_force_discharge.not_implemented"
    return 255
}

batdrv_cancel_force_discharge () {
    # function not implemented for Samsung laptops
    echo_debug "bat" "batdrv.${_batdrv_plugin}.cancel_force_discharge.not_implemented"
    return 255
}

batdrv_force_discharge_active () {
    # function not implemented for Samsung laptops
    echo_debug "bat" "batdrv.${_batdrv_plugin}.force_discharge_active.not_implemented"
    return 255
}

batdrv_discharge () {
    # function not implemented for Samsung laptops

    # Important: release lock from caller
    unlock_tlp tlp_discharge

    echo_debug "bat" "batdrv.${_batdrv_plugin}.discharge.not_implemented"
    return 255
}

batdrv_show_battery_data () {
    # output battery status
    # $1: 1=verbose
    # global param: $_batteries
    # prerequisite: batdrv_init()
    local verbose=${1:-0}

    printf "+++ Battery Care\n"
    printf "Plugin: %s\n" "$_batdrv_plugin"

    if [ "$_bm_thresh" = "natacpi" ]; then
        printf "Supported features: charge threshold\n"
    else
        printf "Supported features: none available\n"
    fi

    printf "Driver usage:\n"
    # vendor specific kernel api
    case $_natacpi in
        0)   printf "* vendor (%s) = active (charge threshold)\n" "$_batdrv_kmod" ;;
        32)  printf "* vendor (%s) = inactive (disabled by configuration)\n" "$_batdrv_kmod" ;;
        128) printf "* vendor (%s) = inactive (no kernel support)\n" "$_batdrv_kmod" ;;
        254) printf "* vendor (%s) = inactive (laptop not supported)\n" "$_batdrv_kmod" ;;
        *)   printf "* vendor (%s) = unknown status\n" "$_batdrv_kmod" ;;
    esac

    if [ "$_bm_thresh" = "natacpi" ]; then
        local th sfx=
        printf "Parameter value range:\n"
        printf "* STOP_CHARGE_THRESH_BAT0: 0(off), 1(on) -- -- battery life extender\n\n"
        if th=$(batdrv_read_threshold); then
            case $th in
                0) sfx=" (100%)" ;;
                1) sfx=" (80%)" ;;
                *) sfx=" (invalid)";;
            esac
            printf "%-59s = %d%s\n" "$_bf_stop" "$th" "$sfx"
        else
            printf "%-59s = %s\n" "$_bf_stop" "(not available)"
        fi
    fi
    printf "\n"

    # -- show battery data
    local bat
    local bcnt=0
    local ed ef en
    local efsum=0
    local ensum=0

    for bat in $_batteries; do # iterate batteries
        batdrv_select_battery "$bat"

        printf "+++ Battery Status: %s\n" "$bat"

        printparm "%-59s = ##%s##" "$_bd_read/manufacturer"
        printparm "%-59s = ##%s##" "$_bd_read/model_name"

        print_battery_cycle_count "$_bd_read/cycle_count" "$(read_sysf "$_bd_read/cycle_count")"

        if [ -f "$_bd_read/energy_full" ]; then
            printparm "%-59s = ##%6d## [mWh]" "$_bd_read/energy_full_design" "" 000
            printparm "%-59s = ##%6d## [mWh]" "$_bd_read/energy_full" "" 000
            printparm "%-59s = ##%6d## [mWh]" "$_bd_read/energy_now" "" 000
            printparm "%-59s = ##%6d## [mW]" "$_bd_read/power_now" "" 000

            # store values for charge / capacity calculation below
            ed=$(read_sysval "$_bd_read/energy_full_design")
            ef=$(read_sysval "$_bd_read/energy_full")
            en=$(read_sysval "$_bd_read/energy_now")
            efsum=$((efsum + ef))
            ensum=$((ensum + en))

        elif [ -f "$_bd_read/charge_full" ]; then
            printparm "%-59s = ##%6d## [mAh]" "$_bd_read/charge_full_design" "" 000
            printparm "%-59s = ##%6d## [mAh]" "$_bd_read/charge_full" "" 000
            printparm "%-59s = ##%6d## [mAh]" "$_bd_read/charge_now" "" 000
            printparm "%-59s = ##%6d## [mA]" "$_bd_read/current_now" "" 000

            # store values for charge / capacity calculation below
            ed=$(read_sysval "$_bd_read/charge_full_design")
            ef=$(read_sysval "$_bd_read/charge_full")
            en=$(read_sysval "$_bd_read/charge_now")
            efsum=$((efsum + ef))
            ensum=$((ensum + en))

        else
            ed=0
            ef=0
            en=0
        fi

        print_batstate "$_bd_read/status"
        printf "\n"

        if [ "$verbose" -eq 1 ]; then
            printparm "%-59s = ##%6s## [mV]" "$_bd_read/voltage_min_design" "" 000
            printparm "%-59s = ##%6s## [mV]" "$_bd_read/voltage_now" "" 000
            printf "\n"
        fi

        # --- show battery features: thresholds

        # --- show charge level (SOC) and capacity
        if [ "$ef" -ne 0 ]; then
            perl -e 'printf ("%-59s = %6.1f [%%]\n", "Charge",   100.0 * '"$en"' / '"$ef"');'
            lf=1
        fi
        if [ "$ed" -ne 0 ]; then
            perl -e 'printf ("%-59s = %6.1f [%%]\n", "Capacity", 100.0 * '"$ef"' / '"$ed"');'
            lf=1
        fi
        [ "$lf" -gt 0 ] && printf "\n"

        bcnt=$((bcnt+1))

    done # for bat

    if [ $bcnt -gt 1 ] && [ $efsum -ne 0 ]; then
        # more than one battery detected --> show charge total
        perl -e 'printf ("%-59s = %6.1f [%%]\n", "+++ Charge total",   100.0 * '"$ensum"' / '"$efsum"');'
        printf "\n"
    fi

    return 0
}

batdrv_recommendations () {
     # no recommendations for Samsung laptops
    return 0
}
