#!/bin/sh

# Systemd generator for redirecting the boot to charger mode.
# See systemd.generator(5).

# Try to use builtins as much as possible. Generators run early in bootup process,
# so better not slow down the boot.

dest_normal=$1
dest_early=$2
dest_late=$3

is_charger_mode() {
    # The boot reason is exported via /proc/cmdline
    # The standard method is using androidboot.mode parameter.

    read -r cmdline </proc/cmdline
    # shellcheck disable=SC2013 # Intend to split words
    for x in ${cmdline}; do
        case ${x} in
        androidboot.mode=*charger*)
            return 0
            ;;
        esac
    done

    ## Some devices may be using 'bootreason', others 'boot_reason'
    ## XXX: Find a better way to handle device specifics here

    # Krillin
    if [ -f /sys/class/BOOT/BOOT/boot/boot_mode ]; then
        read -r boot_reason </sys/class/BOOT/BOOT/boot/boot_mode
        case "${boot_reason}" in
        1) return 0 ;; # Meta
        4) return 0 ;; # Factory
        8) return 0 ;; # Power off charging
        9) return 0 ;; # Low power charging
        esac
    fi

    return 1
}

if is_charger_mode; then
    ln -sf /lib/systemd/system/charger.target "${dest_early}/default.target"
fi
