116 lines
2.2 KiB
Bash
Executable File
116 lines
2.2 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
|
|
set -e
|
|
|
|
function usage() {
|
|
cat << EOF
|
|
usage: ${0##*/} [command]
|
|
charging [on|off] - Toggle charging
|
|
adapter [on|off] - Toggle adapter connection
|
|
status - Get status information
|
|
revert - Revert to default settings
|
|
visudo - Run the script without password
|
|
help - Display this help message
|
|
EOF
|
|
}
|
|
|
|
function enable_discharging() {
|
|
echo "Enabling battery discharging"
|
|
sudo smc -k CH0I -w 01
|
|
}
|
|
|
|
function disable_discharging() {
|
|
echo "Disabling battery discharging"
|
|
sudo smc -k CH0I -w 00
|
|
}
|
|
|
|
function enable_charging() {
|
|
echo "Enabling battery charging"
|
|
sudo smc -k CH0B -w 00
|
|
sudo smc -k CH0C -w 00
|
|
disable_discharging
|
|
}
|
|
|
|
function disable_charging() {
|
|
echo "Disabling battery charging"
|
|
sudo smc -k CH0B -w 02
|
|
sudo smc -k CH0C -w 02
|
|
}
|
|
|
|
function get_smc_charging_hex() {
|
|
smc -k CH0B -r | awk '{print $4}' | sed 's:\)::'
|
|
}
|
|
|
|
function get_smc_charging_status() {
|
|
hex_status=$(get_smc_charging_hex)
|
|
if [[ "$hex_status" == "00" ]]; then
|
|
echo "enabled"
|
|
else
|
|
echo "disabled"
|
|
fi
|
|
}
|
|
|
|
function get_battery_percentage() {
|
|
battery_percentage=$(pmset -g batt | tail -n1 | awk '{print $3}' | sed 's:%\;::')
|
|
echo "$battery_percentage"
|
|
}
|
|
|
|
function install_visudo_file() {
|
|
sudoers_file=/private/etc/sudoers.d/cbattery
|
|
sudo cp "$1" "$sudoers_file"
|
|
sudo chmod 440 "$sudoers_file"
|
|
}
|
|
|
|
action=$1
|
|
setting=$2
|
|
|
|
if [ -z "$action" ] || [[ "$action" == "help" ]]; then
|
|
usage
|
|
exit 0
|
|
fi
|
|
|
|
if [[ "$action" == "revert" ]]; then
|
|
enable_charging
|
|
disable_discharging
|
|
exit 0
|
|
fi
|
|
|
|
if [[ "$action" == "charging" ]]; then
|
|
echo "Setting $action to $setting"
|
|
if [[ "$setting" == "on" ]]; then
|
|
enable_charging
|
|
elif [[ "$setting" == "off" ]]; then
|
|
disable_charging
|
|
fi
|
|
exit 0
|
|
fi
|
|
|
|
if [[ "$action" == "adapter" ]]; then
|
|
echo "Setting $action to $setting"
|
|
if [[ "$setting" == "on" ]]; then
|
|
enable_discharging
|
|
elif [[ "$setting" == "off" ]]; then
|
|
disable_discharging
|
|
fi
|
|
exit 0
|
|
fi
|
|
|
|
if [[ "$action" == "status" ]]; then
|
|
if [[ "$setting" == "charging" ]]; then
|
|
exit "$(get_smc_charging_hex)"
|
|
else
|
|
echo "Battery at $(get_battery_percentage)%, smc charging $(get_smc_charging_status)"
|
|
fi
|
|
exit 0
|
|
fi
|
|
|
|
if [[ "$action" == "visudo" ]]; then
|
|
if [[ -n "$setting" ]]; then
|
|
install_visudo "$setting"
|
|
else
|
|
install_visudo ".visudo"
|
|
fi
|
|
exit 0
|
|
fi
|
|
|