chezmoi-ify

This commit is contained in:
Barak Michener 2024-05-18 18:26:23 -07:00
parent b419ec8f9f
commit e04f3e0fb8
13 changed files with 0 additions and 5859 deletions

4985
bin/ack

File diff suppressed because it is too large Load diff

View file

@ -1,158 +0,0 @@
#!/usr/bin/env perl
# Copyright J.M.P. Alves 2008-2011 (jmalves@vcu.edu)
# This software is licensed under the GNU General Public License v. 3
# Please see http://www.fsf.org/licensing/licenses/gpl.html for details
# first version 0.2, 2008-03-24, by J.
# Last update 0.7 2011-07-29, by J.
use strict;
use warnings;
use Getopt::Long;
Getopt::Long::Configure ("bundling");
my($A,$s,$t,$l,$m,$h,$v,$d,$x,$n,$E,$c);
GetOptions ('a' => \$A, 's' => \$s, 't' => \$t, 'l' => \$l, 'x' => \$x, 'e' => \$E,
'n' => \$n, 'm' => \$m, 'h' => \$h, 'v' => \$v, 'd=i' => \$d, 'c=i' => \$c);
my @vals;
my $version = "0.7.1";
if($h) { print "Version: $version\n\n"; Help(); }
if($v) { print "$version\n"; exit; }
my $type = $E ? "E" : "f";
$c = $c ? $c - 1 : 0;
unless(defined $d) { $d = "2$type"; } else { $d .= "$type"; }
while(<>) {
next if $_ =~ /^\s*$/;
chomp;
$_ =~ s/^\s*//;
my @tmp = split(/\s+|\t+/, $_);
unless($tmp[$c] =~ /^\s*[+\-\d\.]+\s*$/ || $tmp[$c] =~ /^\s*[+\-\d\.e]+\s*$/i) { next; }
my $flag = 0;
local $SIG{__WARN__} = sub {
print "WARNING: Possible non-numeric value found, ignored: $_\n";
$flag = 1;
};
my $test = $tmp[$c] + 1;
unless($flag) { push @vals, $tmp[$c]; }
}
unless(scalar(@vals)) { print STDERR "ERROR: No numerical values found. I quit.\n"; exit; }
if(scalar(@vals) == 1) { print STDERR "ERROR: Only one numerical value (@vals) found. Nothing to do, so I quit.\n"; exit; }
my($sum, $av, $sd, $median, $min, $max);
($sum, $av) = avrg(@vals);
$sd = stddev($av, @vals);
($median,$min,$max) = median(@vals);
if($l || !($A || $s || $t || $m || $x || $n)) {
printf "%.$d +/- %.$d, total %.$d, median %.$d, minimum %.$d, maximum %.$d, n = %d\n", $av, $sd, $sum, $median, $min, $max, scalar(@vals);
exit;
}
if($A && !$s) { printf "%.$d\n", $av; exit; }
if($s) { printf "%.$d\t%.$d\n", $av, $sd; exit; }
if($t) { printf "%.$d\n", $sum; exit; }
if($m) { printf "%.$d\n", $median; exit; }
if($n) { printf "%.$d\n", $min; exit; }
if($x) { printf "%.$d\n", $max; exit; }
exit;
##############################
sub avrg {
my $size = scalar(@_);
my($sum,$med);
for my $Valor (@_) { $sum += $Valor; }
if ($size) { $med = $sum/$size; }
else { $med = 0; }
return $sum, $med;
}
##############################
sub stddev {
my($media) = shift(@_);
my(@Lista) = @_;
my $nonzero = 0;
my($sum,$sd);
for ($a=0; $a < scalar(@Lista); $a++) {
$nonzero++;
$sum += (($Lista[$a] - $media) ** 2);
}
if ($nonzero) { $sd = sqrt($sum/($nonzero-1)); }
else { $sd = 0; }
return $sd;
}
##############################
sub median {
my @list = sort {$a<=>$b} @_;
if(scalar(@list) % 2 != 0) {
my $ind = int(scalar(@list)/2);
return $list[$ind], $list[0], $list[$#list];
}
else {
my $ind = scalar(@list)/2 -1;
my(undef, $median) = avrg($list[$ind],$list[$ind+1]);
return $median, $list[0], $list[$#list];
}
}
##############################
sub Help {
my (@stuff) = <DATA>;
print @stuff;
exit;
}
##############################
__DATA__
average
-------
Usage:
average [options]
Synopsis:
Takes a series of numbers and calculates simple statistics: average (arithmetic
mean), standard deviation, median, total sum, and minimum and maximum values
present. For version 0.6 and later, also works with scientific notation numbers.
Numbers can be in a file or presented from standard input (press control-d
to end number input after last number). Output is to standard output.
Input can also have more than one column, in which case the column to use
in calculations can be determined using the -c option. Otherwise, the first
column is used (leading spaces are ignored; repeated whitespace is considered
as one).
Options:
-d Number of decimal places to show (default: 2);
-c Column to use for calculations (default: 1);
-e Output in scientific notation (e.g. 1E12);
-a Shows only the arithmetic mean;
-s Shows arithmetic mean and the standard deviation;
-t Shows only the total sum of the numbers;
-m Shows only the median;
-n Shows only the minimum value;
-x Shows only the maximum value;
-l Long format, presenting all of the above (default);
-v Prints program version and exits;
-h Prints this help message and exits.
* Options listed first have precedence over the ones below; e.g. if the user
uses both -t and -n, only -t will have an effect (total sum only will be shown).
* If average is used without any options, all statistics are shown (same as -l).
Copyright J.M.P. Alves 2008-2011 (jmalves@vcu.edu)
This software is licensed under the GNU General Public License v. 3.
Please see http://www.fsf.org/licensing/licenses/gpl.html for details.

View file

@ -1,132 +0,0 @@
#!/bin/sh
HEART_FULL=♥
HEART_EMPTY=♡
[ -z "$NUM_HEARTS" ] &&
NUM_HEARTS=5
cutinate()
{
perc=$1
inc=$(( 100 / $NUM_HEARTS))
for i in `seq $NUM_HEARTS`; do
if [ $perc -lt 100 ]; then
echo $HEART_EMPTY
else
echo $HEART_FULL
fi
perc=$(( $perc + $inc ))
done
}
linux_get_bat ()
{
echo $(( $BAT_TOTAL / $BAT_COUNT ))
}
openbsd_get_bat ()
{
bf=$(sysctl -n hw.sensors.acpibat0.amphour0 | cut -d ' ' -f 1)
bn=$(sysctl -n hw.sensors.acpibat0.amphour3 | cut -d ' ' -f 1)
echo "(($bn * 100) / $bf)" | bc -l | awk -F '.' '{ print $1 }';
}
freebsd_get_bat ()
{
sysctl -n hw.acpi.battery.life
}
battery_status()
{
case $(uname -s) in
"Linux")
BATTERIES=$(ls /sys/class/power_supply | grep BAT)
BAT_COUNT=$(ls /sys/class/power_supply | grep BAT | wc -l)
[ $BAT_COUNT -eq 0 ] && return
for BATTERY in $BATTERIES; do
BAT_PATH=/sys/class/power_supply/$BATTERY
STATUS=$BAT_PATH/status
[ "$1" = `cat $STATUS` ] || [ "$1" = "" ] || return 0
if [ -f "$BAT_PATH/energy_full" ]; then
naming="energy"
elif [ -f "$BAT_PATH/charge_full" ]; then
naming="charge"
elif [ -f "$BAT_PATH/capacity" ]; then
cat "$BAT_PATH/capacity"
return 0
fi
BAT_PERCENT=$(( 100 * $(cat $BAT_PATH/${naming}_now) / $(cat $BAT_PATH/${naming}_full) ))
BAT_TOTAL=$(( ${BAT_TOTAL-0} + $BAT_PERCENT ))
done
linux_get_bat
;;
"FreeBSD")
STATUS=`sysctl -n hw.acpi.battery.state`
case $1 in
"Discharging")
if [ $STATUS -eq 1 ]; then
freebsd_get_bat
fi
;;
"Charging")
if [ $STATUS -eq 2 ]; then
freebsd_get_bat
fi
;;
"")
freebsd_get_bat
;;
esac
;;
"OpenBSD")
openbsd_get_bat
;;
"Darwin")
case $1 in
"Discharging")
ext="No";;
"Charging")
ext="Yes";;
esac
ioreg -c AppleSmartBattery -w0 | \
grep -o '"[^"]*" = [^ ]*' | \
sed -e 's/= //g' -e 's/"//g' | \
sort | \
while read key value; do
case $key in
"MaxCapacity")
export maxcap=$value;;
"CurrentCapacity")
export curcap=$value;;
"ExternalConnected")
if [ -n "$ext" ] && [ "$ext" != "$value" ]; then
exit
fi
;;
"FullyCharged")
if [ "$value" = "Yes" ]; then
exit
fi
;;
esac
if [[ -n "$maxcap" && -n $curcap ]]; then
echo $(( 100 * $curcap / $maxcap ))
break
fi
done
esac
}
BATTERY_STATUS=`battery_status $1`
[ -z "$BATTERY_STATUS" ] && exit
if [ -n "$CUTE_BATTERY_INDICATOR" ]; then
cutinate $BATTERY_STATUS
else
echo ${BATTERY_STATUS}%
fi

View file

@ -1,13 +0,0 @@
#!/usr/bin/ruby
x = readline()
x = x.strip
(x.length() + 4).times {print "*"}
print "\n"
print "* "
print x
print " *\n"
(x.length() + 4).times {print "*"}
print "\n"

View file

@ -1,34 +0,0 @@
#!/usr/bin/env python2
import sys
loadfile = sys.stdin
if len(sys.argv) == 1:
print("No command to run")
sys.exit(1)
if len(sys.argv) == 3:
if sys.argv[2] != "-":
loadfile = open(sys.argv[2])
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mult(x, y):
return x * y
def div(x,y):
return x / y;
lis = []
for line in loadfile:
if line.strip() is not "":
x = float(line)
lis.append(x)
print reduce(eval(sys.argv[1]), lis)

View file

@ -1,48 +0,0 @@
#!/bin/bash
# Cronic v2 - cron job report wrapper
# Copyright 2007 Chuck Houpt. No rights reserved, whatsoever.
# Public Domain CC0: http://creativecommons.org/publicdomain/zero/1.0/
set -eu
OUT=/tmp/cronic.out.$$
ERR=/tmp/cronic.err.$$
TRACE=/tmp/cronic.trace.$$
set +e
"$@" >$OUT 2>$TRACE
RESULT=$?
set -e
PATTERN="^${PS4:0:1}\\+${PS4:1}"
if grep -aq "$PATTERN" $TRACE
then
! grep -av "$PATTERN" $TRACE > $ERR
else
ERR=$TRACE
fi
if [ $RESULT -ne 0 -o -s "$ERR" ]
then
echo "Cronic detected failure or error output for the command:"
echo "$@"
echo
echo "RESULT CODE: $RESULT"
echo
echo "ERROR OUTPUT:"
cat "$ERR"
echo
echo "STANDARD OUTPUT:"
cat "$OUT"
if [ $TRACE != $ERR ]
then
echo
echo "TRACE-ERROR OUTPUT:"
cat "$TRACE"
fi
fi
rm -f "$OUT"
rm -f "$ERR"
rm -f "$TRACE"

View file

@ -1,63 +0,0 @@
#!/usr/bin/env python3
import subprocess
import sys
import os
from typing import List, Dict, Any
DataLine = Dict[Any, Any]
def grab_blame_data() -> List[DataLine]:
p = subprocess.check_output(
["git", "blame", "--line-porcelain"] + sys.argv[1:],
encoding='utf-8',
)
data = []
cur = {}
p = str(p)
in_segment = False
for line in p.splitlines():
l = line.rstrip()
if len(l) == 0:
continue
if l[0] == '\t':
cur["data"] = l[1:]
data.append(cur)
cur = {}
in_segment = False
continue
d = l.split()
if not in_segment:
cur["sha"] = d[0]
cur["sha8"] = d[0][:8]
in_segment = True
else:
cur[d[0]] = " ".join(d[1:])
assert in_segment is False
return data
FIELDS = ["sha8", "author", "summary", "data"]
def main() -> None:
d = grab_blame_data()
lens = {}
for f in FIELDS:
maxn = 0
for x in d:
if len(x[f]) > maxn:
maxn = len(x[f])
lens[f] = maxn
for x in d:
s = ""
for f in FIELDS:
s = s + x[f].ljust(lens[f]) + ' '
print(s)
if __name__ == "__main__":
main()

View file

@ -1,22 +0,0 @@
#!/usr/bin/env perl
use strict;
use warnings;
my $a = join(" ", @ARGV);
my $cmd = "golint " . $a;
open(my $fh, '-|', $cmd)
or die "Could not run golint";
my $cnt = 0;
while (my $row = <$fh>) {
chomp $row;
if ($row !~ /should have comment or be unexported/) {
print "$row\n";
$cnt++;
}
}
if ($cnt > 0) {
exit 1;
}
exit 0;

119
bin/orly
View file

@ -1,119 +0,0 @@
#!/usr/bin/perl
#
# Globals
#
use vars qw/$deftext %opt /;
#
# Command line options processing
#
sub init()
{
use Getopt::Std;
my $opt_string = 'hdoynsi';
getopts( "$opt_string", \%opt ) or usage();
usage() if $opt{h};
}
#
# Message about this program and how to use it
#
sub usage()
{
print STDERR << "EOF";
orly -- Print an O RLY owl
usage: $0 [-hdoyn] [<MESSAGE>]
-h : this (help) message
-o, -d : print the "O RLY" owl
-y : print the "YA RLY" owl
-n : print the "NO WAI!" owl
-s : Print "SRSLY" as a question, statement or
exclamation, respectively for the above.
-i : take MESSAGE from STDIN
EOF
exit;
}
sub printorly() {
$deftext = "O RLY?";
print << "EOO"
___
{o,o}
|)__)
-"-"-
EOO
}
sub printyarly() {
$deftext = "YA RLY";
print << "EOO"
___
{o.o}
|)_(|
-"-"-
EOO
}
sub printnowai() {
$deftext = "NO WAI!";
print << "EOO"
___
{o,o}
(__(|
-"-"-
EOO
}
$givenstatement = "";
for ($i=0; $i<($#ARGV + 1); $i++)
{
if (substr($ARGV[$i],0,1) ne "-")
{
$up = uc($ARGV[$i]);
$givenstatement = "$givenstatement$up ";
}
}
init();
if ($opt{i}) {
while (<STDIN>) {
$givenstatement = $givenstatement.uc($_);
}
chomp($givenstatement);
}
if ($opt{y}) {
printyarly();
$deftext = "SRSLY" if ($opt{s});
}
elsif ($opt{n}) {
printnowai();
$deftext = "SRSLY!" if ($opt{s});
}
elsif ($opt{d} || $opt {o}) {
printorly();
$deftext = "SRSLY?" if ($opt{s});
}
elsif ($opt{s}) {
printyarly();
$deftext = "SRSLY";
}
else {
printorly();
}
if ($givenstatement)
{
print "$givenstatement\n";
}
else
{
print "$deftext\n";
}
exit;

61
bin/pk
View file

@ -1,61 +0,0 @@
#!/bin/sh
search () {
shift
if command -v pacman &> /dev/null; then
pacman -Ss $1 || yay -Ss $1
elif command -v dnf &> /dev/null; then
dnf search $1
elif command -v port &> /dev/null; then
port search $1
elif command -v portmaster &> /dev/null; then
cd /usr/ports
make search name=$1 | grep "^\(Port\|Path\|Info\|Moved\|$\)"
elif command -v aptitude &> /dev/null; then
aptitude search $1
elif command -v apt-cache &> /dev/null; then
apt-cache search $1
fi
}
update () {
shift
if command -v pacman &> /dev/null; then
sudo pacman -Sy
elif command -v dnf &> /dev/null; then
sudo dnf update
elif command -v port &> /dev/null; then
sudo port selfupdate
elif command -v portsnap &> /dev/null; then
sudo portsnap fetch && sudo portsnap upgrade
elif command -v apt-get &> /dev/null; then
sudo apt-get update
fi
}
install () {
shift
if command -v pacman &> /dev/null; then
sudo pacman -S $* || yay -S $*
elif command -v dnf &> /dev/null; then
sudo dnf install $*
elif command -v port &> /dev/null; then
sudo port install $*
elif command -v portmaster &> /dev/null; then
sudo portmaster $*
elif command -v apt-get &> /dev/null; then
sudo apt-get install $*
fi
}
case $1
in
"i" | "install")
install $*;;
"s" | "search")
search $*;;
"u" | "update")
update $*;;
esac

View file

@ -1,35 +0,0 @@
#!/usr/bin/env python2
#
# They Fight Crime!
#
# taken from the Javascript at
# http://home.epix.net/~mhryvnak/theyfightcrime.html
# and translated into python by B. Michener
#
import random
#init a;
a = [0, 1, 2, 3, 4, 5, 6, 7]
for i in range(0,8):
a[i] = random.randint(0,39)
he1 = ["a superhumanly strong","an underprivileged","a globe-trotting","an impetuous","a shy","a suave","a notorious","a one-legged","an all-American","a short-sighted","an otherworldly","a hate-fuelled","a scrappy","an unconventional","a jaded","a leather-clad","a fiendish","a Nobel prize-winning","a suicidal","a maverick","a bookish","an old-fashioned","a witless","a lounge-singing","a war-weary","a scarfaced","a gun-slinging","an obese","a time-tossed","a benighted","an uncontrollable","an immortal","an oversexed","a world-famous","an ungodly","a fast talking","a deeply religious","a lonely","a sword-wielding","a genetically engineered"]
he2 = ["white trash","zombie","shark-wrestling","playboy","guitar-strumming","Jewish","sweet-toothed","bohemian","crooked","chivalrous","moralistic","amnesiac","devious","drug-addicted","voodoo","Catholic","overambitious","coffee-fuelled","pirate","misogynist","skateboarding","arachnophobic","Amish","small-town","Republican","one-eyed","gay","guerilla","vegetarian","dishevelled","alcoholic","flyboy","ninja","albino","hunchbacked","neurotic","umbrella-wielding","native American","soccer-playing","day-dreaming"]
he3 = ["grifter","stage actor","paramedic","gentleman spy","jungle king","hairdresser","photographer","ex-con","vagrant","filmmaker","werewolf","senator","romance novelist","shaman","cop","rock star","farmboy","cat burglar","cowboy","cyborg","inventor","assassin","boxer","dog-catcher","master criminal","gangster","firefighter","househusband","dwarf","librarian","paranormal investigator","Green Beret","waffle chef","vampire hunter","messiah","astronaut","sorceror","card sharp","matador","barbarian"]
he4 = ["with a robot buddy named Sparky.","whom everyone believes is mad.","gone bad.","with a mysterious suitcase handcuffed to his arm.","living undercover at Ringling Bros. Circus.","searching for his wife's true killer.","who dotes on his loving old ma.","looking for 'the Big One.'","who knows the secret of the alien invasion.","on the edge.","on a mission from God.","with a secret.","in drag.","","plagued by the memory of his family's brutal murder.","looking for a cure to the poison coursing through his veins.","moving from town to town, helping folk in trouble.","who must take medication to keep him sane.","who hangs with the wrong crowd.","possessed of the uncanny powers of an insect.","with a winning smile and a way with the ladies.","fleeing from a secret government programme.","from the 'hood.","haunted by an iconic dead American confidante","with a passion for fast cars.","trapped in a world he never made.","in a wheelchair.","on the hunt for the last specimen of a great and near-mythical creature.","on the run.","for the 21st century.","who hides his scarred face behind a mask.","on the wrong side of the law.","with no name.","from the Mississippi delta.","with acid for blood.","with nothing left to lose.","haunted by memories of 'Nam.","on a search for his missing sister.","on his last day in the job.","from a doomed world.","who believes he can never love again."]
she1 = ["a radical","a green-fingered","a tortured","a time-travelling","a vivacious","a scantily clad","a mistrustful","a violent","a transdimensional","a strong-willed","a ditzy","a man-hating","a high-kicking","a blind","an elegant","a supernatural","a foxy","a bloodthirsty","a cynical","a beautiful","a plucky","a sarcastic","a psychotic","a hard-bitten","a manipulative","an orphaned","a cosmopolitan","a chain-smoking","a cold-hearted","a warm-hearted","a sharp-shooting","an enchanted","a wealthy","a pregnant","a mentally unstable","a virginal","a brilliant","a disco-crazy","a provocative","an artistic"]
she2 = ["tempestuous","Buddhist","foul-mouthed","nymphomaniac","green-skinned","impetuous","African-American","punk","hypochondriac","junkie","blonde","goth","insomniac","gypsy","mutant","renegade","tomboy","French-Canadian","motormouth","belly-dancing","communist","hip-hop","thirtysomething","cigar-chomping","extravagent","out-of-work","Bolivian","mute","cat-loving","snooty","wisecracking","red-headed","winged","kleptomaniac","antique-collecting","psychic","gold-digging","bisexual","paranoid","streetsmart"]
she3 = ["archaeologist","pearl diver","mechanic","detective","hooker","femme fatale","former first lady","barmaid","fairy princess","magician's assistant","schoolgirl","college professor","angel","bounty hunter","opera singer","cab driver","soap star","doctor","politician","lawyer","nun","snake charmer","journalist","bodyguard","vampire","stripper","Valkyrie","wrestler","mermaid","single mother","safe cracker","traffic cop","research scientist","queen of the dead","Hell's Angel","museum curator","advertising executive","widow","mercenary","socialite"]
she4 = ["on her way to prison for a murder she didn't commit.","trying to make a difference in a man's world.","with the soul of a mighty warrior.","looking for love in all the wrong places.","with an MBA from Harvard.","who hides her beauty behind a pair of thick-framed spectacles.","with the power to see death.","descended from a line of powerful witches.","from a family of eight older brothers.","with a flame-thrower.","with her own daytime radio talk show.","living on borrowed time.","who can talk to animals.","prone to fits of savage, blood-crazed rage.","who don't take no shit from nobody.","with a knack for trouble.","who believes she is the reincarnation of an ancient Egyptian queen.","fleeing from a Satanic cult.","on the trail of a serial killer.","with a birthmark shaped like Liberty's torch.","in the witness protection scheme.","from out of town.","from aristocratic European stock.","living homeless in New York's sewers.","with only herself to blame.","from beyond the grave","married to the Mob.","from the wrong side of the tracks.","from a secret island of warrior women.","from Mars.","with someone else's memories.","from a different time and place.","operating on the wrong side of the law.","who inherited a spooky stately manor from her late maiden aunt.","who dreams of becoming Elvis.","with a song in her heart and a spring in her step.","in the wrong place at the wrong time.","with an incredible destiny.","with the power to bend men's minds.","with an evil twin sister."]
print "He's " + he1[a[0]] + " " + he2[a[1]] + " " + he3[a[2]] + " " + he4[a[3]],
print "She's " + she1[a[4]] + " " + she2[a[5]] + " " + she3[a[6]] + " " + she4[a[7]],
print "They fight crime!"

8
bin/vi
View file

@ -1,8 +0,0 @@
#!/bin/sh
export TERM=xterm-256color
if [ -n "`which nvim`" ]; then
exec -a nvim nvim "$@"
else
exec -a vim vim "$@"
fi

View file

@ -1,181 +0,0 @@
#!/bin/bash
debug() {
# DEBUG comes from the environment
if (( DEBUG )); then
printf '%s\n' "$@" >&2
fi
}
is_enabled() {
local id="${1?}"
enabled=$(
xinput list-props "$id" |
grep '\bDevice Enabled\b' | sed 's/.*\(.\)$/\1/'
)
# xinput returns 0 for disabled and 1 for enabled, so we invert since we
# pass on 0
return "$(( !enabled ))"
}
should_disable() {
local id="${1?}"
local force_enable="${2?}"
local force_disable="${3?}"
if (( force_enable )) && (( force_disable )); then
echo '-d and -e make no sense together' >&2
exit 3
fi
if (( force_enable )); then
return 1
elif (( force_disable )); then
return 0
elif is_enabled "$id"; then
return 0
else
return 1
fi
}
get_id_for_device_name() {
local name="${1?}"
xinput list "$name" | sed -n 's/.*id=\([0-9]\+\).*/\1/p'
}
show_help() {
cat << EOF
Usage: ${0##*/} [-n]
Enable and disable xinput devices.
-d disable only, do not toggle
-e enable only, do not toggle
-h show this help page
-i XID only operate on device with xinput id XID
-r REGEX only operate on devices matching name REGEX
-n show results using notify-send in addition to stdout
-p print what we would do, but don't actually do it
-t SECONDS revert enable/disable after SECONDS seconds, ie. if you were
enabling, after SECONDS seconds it will be disabled again.
SECONDS must be an integer greater than 0
EOF
}
act_on_device() {
local print="${1?}"
local notify="${2?}"
local timeout="${3?}"
local xinput_action="${4?}"
local our_next_flag="${5?}"
local id="${6?}"
if (( print )); then
echo "Would $xinput_action device with id $id"
else
xinput -"$xinput_action" "$id"
if (( notify )); then
notify-send "${xinput_action^}d device with id $id"
fi
if (( timeout )); then
debug "Added timeout $timeout"
{
sleep "$timeout"
# TODO: Make args_without_timeour_or_force non-global (sigh,
# shell makes this difficult due to pass by value)
"$0" "${args_without_timeout_or_force[@]}" \
"$our_next_flag" -i "$id"
} &
fi
fi
}
notify=0
force_enable=0
force_disable=0
timeout=0
print=0
only_xid=0
input_ids=()
args_without_timeout_or_force=()
while getopts dehi:npr:t: opt; do
# We need to get a list of args without timeout/force for when we execute
# timeout reversions. This is a blacklist of things we should not put in
# the array, since they force enable/disable/name or do the timeout itself.
case "$opt" in
d|e|t|r)
: # Blacklisted
;;
*)
args_without_timeout_or_force+=( -"$opt" )
if [[ $OPTARG ]]; then
args_without_timeout_or_force+=( "$OPTARG" )
fi
;;
esac
case "$opt" in
'd') force_disable=1 ;;
'e') force_enable=1 ;;
'n') notify=1 ;;
'i') only_xid="$OPTARG" ;;
'h')
show_help
exit 0
;;
'p') print=1 ;;
'r') regex="$OPTARG" ;;
't') timeout="$OPTARG" ;;
'?')
show_help >&2
exit 1
;;
esac
done
if (( only_xid )) && [[ "$regex" ]]; then
echo '-r and -i cannot be currently used together' >&2
exit 4
elif ! (( only_xid )) && ! [[ "$regex" ]]; then
echo 'either -r or -i must be passed to filter devices' >&2
exit 5
fi
if (( only_xid )); then
input_ids=( "$only_xid" )
else
mapfile -t matched_device_names < <(
xinput list |
sed -n 's/.*↳ \(.\+\)id=.*\[slave.*/\1/p' |
sed 's/[\t ]*$//' |
grep -i -- "$regex"
)
debug 'Matched device names:' "${matched_device_names[@]}"
for name in "${matched_device_names[@]}"; do
input_ids+=( "$(get_id_for_device_name "$name")" )
done
fi
if (( "${#input_ids[@]}" == 0 )); then
msg='No matching devices found'
echo "$msg" >&2
(( notify )) && notify-send "$msg"
exit 2
fi
for id in "${input_ids[@]}"; do
if should_disable "$id" "$force_enable" "$force_disable"; then
act_on_device "$print" "$notify" "$timeout" disable -e "$id"
else
act_on_device "$print" "$notify" "$timeout" enable -d "$id"
fi
done
# We may have queued some timeout reversion jobs
wait