#!/usr/bin/env -S awk -f
# -*- mode: awk -*-
function get_icon(charge) {
    if (charge <= 10) {
        return "󰂃";
    } else if (charge <= 20) {
        return "󰁻";
    } else if (charge <= 30) {
        return "󰁼";
    } else if (charge <= 40) {
        return "󰁽";
    } else if (charge <= 50) {
        return "󰁾";
    } else if (charge <= 60) {
        return "󰁿";
    } else if (charge <= 70) {
        return "󰂀";
    } else if (charge <= 80) {
        return "󰂁";
    } if (charge < 100) {
        return "󰂂";
    } else {
        return "󰁹"
    }
}

function notify_send(title, desc, id) {
    if (!id) {
        cmd="dunstify -t 0 -p \"" title "\" \"" desc "\""
        while ((cmd | getline id) > 0) { }
        close(cmd)
    } else {
        system("dunstify -r " id " \"" title "\" \"" desc "\"")
    }
    return id
}

function close_notify(id) {
    system("dunstify -C " id)
}

function warn_if_low() {
    percentage = state_info["percentage"]
    id = state_info["id"]
    notified = state_info["notified"]
    if (percentage <= 10) {
        if (!notified) {
            state_info["id"] = notify_send("Battery Low", percentage "%", id)
            state_info["notified"] = 1
        }
    } else if (notified) {
        close_notify(id)
        state_info["notified"] = 0
    }
}

function print_state() {
    percentage = state_info["percentage"]
    printf "%s%s%d%%\n",
           get_icon(percentage),
           state_info["charging"] ? "󱐋" : "",
           percentage
    fflush()
}

function parse_record(record, exit_on_absent) {
    split(record, fields)
    for (i in fields) {
        match(fields[i], /^ *([^:]+): *(.+)$/, parts)
        if (length(parts) >= 3) {
            props[parts[1]] = parts[2]
        }
    }
    name = props["native-path"]
    if (name == "") {
        return 0
    } else if ((! BATTERY && props["power supply"] == "yes" && \
         props["native-path"] ~ /BAT[0-9]+/) || name == BATTERY) {
        state_info["percentage"] = props["percentage"] + 0
        return 1
    } else if ((! ADAPTER && props["power supply"] == "yes" && \
                props["native-path"] ~ /ADP[0-9]+/) || name == ADAPTER) {
        state_info["charging"] = (props["online"] == "yes")
        return 1
    } else {
        return 0
    }
}

function print_initial_stats() {
    cmd = "upower --dump"
    found = 0
    while ((cmd | getline record) > 0) {
        if (record ~ /Device: \/org\/freedesktop\/UPower\/devices\// \
            && parse_record(record)) {
            found = 1
        }
    }
    close(cmd)
    if (! found) {
        # we found no battery adapters
        exit 1
    }
    print_state()
    warn_if_low()
}

BEGIN {
    RS = ""
    FS = "\n"
    print_initial_stats()
    cmd = "upower --monitor-detail"
    while ((cmd | getline record) > 0) {
        if (record ~ /device changed/) {
            parse_record(record)
            print_state()
            warn_if_low()
        }
    }
    close(cmd)
}