Add some scripts

This commit is contained in:
ItsDrike 2021-07-14 15:33:36 +02:00
parent 0c743e32e7
commit a28743931c
No known key found for this signature in database
GPG key ID: B5F6B41F708C3ADD
4 changed files with 275 additions and 0 deletions

63
home/.local/bin/brightness Executable file
View file

@ -0,0 +1,63 @@
#!/bin/sh
BRIGHTNESS_FILE="/sys/class/backlight/intel_backlight/brightness"
BRIGHTNESS_MAX=937
function change_brightness() {
BRIGHTNESS=$(cat $BRIGHTNESS_FILE)
change_value=$2
# If we're dealing with percentages, convert to absolutes
if [ $3 == "%" ]; then
change_value=$((($BRIGHTNESS_MAX / 100) * $change_value))
elif [ $3 == "#" ]; then
change_value=$change_value
else
echo "Invalid unit, options: [% - percent, # - absolute], default: %"
exit 1
fi
# Increment or decrement based on first arg
if [ $1 == "+" ]; then
new_brightness=$(($BRIGHTNESS + $change_value))
elif [ $1 == "-" ]; then
new_brightness=$(($BRIGHTNESS - $change_value))
else
echo "Invalid operator, options: [+, -]"
exit 1
fi
# Make sure we respect min/max boundaries
if [ $new_brightness -lt 0 ]; then
new_brightness=0
elif [ $new_brightness -gt $BRIGHTNESS_MAX ]; then
new_brightness=$BRIGHTNESS_MAX
fi
# Write the brightness (sudo shouldn't require password here)
echo $new_brightness | sudo tee $BRIGHTNESS_FILE
}
if [ $# -ge 1 ] && [ "$1" == "+" ] || [ "$1" == "-" ]; then
if [ $# -lt 2 ]; then
change_value=5 # Default to 5%
else
change_value=$2
fi
if [ $# -lt 3 ]; then
unit="%"
else
unit=$3
fi
change_brightness $1 $change_value $unit > /dev/null
fi
# Display new brightness
BRIGHTNESS=$(cat $BRIGHTNESS_FILE)
BRIGHTNESS_PERCENT=$(echo "($BRIGHTNESS / $BRIGHTNESS_MAX) * 100" | bc -l)
BRIGHTNESS_PERCENT=$(printf "%.2f" $BRIGHTNESS_PERCENT)
echo "Brightness: ${BRIGHTNESS_PERCENT}% (absolute: $BRIGHTNESS)"

119
home/.local/bin/emerge-time Executable file
View file

@ -0,0 +1,119 @@
#!/usr/bin/env python3
import sys
import subprocess
from datetime import datetime
from dataclasses import dataclass
@dataclass
class CompiledPackage:
name: str
date: datetime
compile_time: int
def __repr__(self) -> str:
name = self.name
date = self.date.strftime("%a %b %d %H:%M:%S %Y")
compile_time = get_readable_duration(self.compile_time)
return f"CompiledPackage({name=}, {date=}, {compile_time=})"
def parse_time(time_line: str) -> int:
"""Parse a line that contains time info, return seconds"""
time = 0
words = time_line.split()
if "hour" in words[1]:
time += int(words[0]) * 60 * 60
elif "minute" in words[1]:
time += int(words[0]) * 60
elif "second" in words[1]:
time += int(words[0])
try:
if "second" in words[3]:
time += int(words[2])
elif "minute" in words[3]:
time += int(words[2]) * 60
except IndexError:
pass
return time
def get_readable_duration(total_seconds: int) -> str:
"""Get readable time duration string from total seconds"""
hours, rem = divmod(total_seconds, 3600)
minutes, rem = divmod(rem, 60)
seconds = rem
output = []
if hours > 0:
output.append(f"{hours} hour{'s' if hours > 1 else ''}")
if minutes > 0:
output.append(f"{minutes} minute{'s' if minutes > 1 else ''}")
if seconds > 0:
output.append(f"{seconds} second{'s' if seconds > 1 else ''}")
if len(output) > 1:
output.insert(-1, "and")
return " ".join(output)
def get_packages() -> list[CompiledPackage]:
"""Obtain compilation times for every compiled package"""
x = subprocess.run(
"sudo genlop -nlt",
stdout=subprocess.PIPE,
shell=True
)
txt = x.stdout.decode("utf-8")
# Cleanup the output
txt = txt.replace("* packages merged:\n\n", "")
txt = txt.replace("merge time: ", "")
txt = txt.replace("and ", "")
txt = txt.replace(".", "")
# Remove indents
clean_lines = [line.lstrip() for line in txt.split("\n")]
txt = "\n".join(clean_lines)
# Store (package name, date, compile time) for each package
packages = []
for pkg_txt in txt.split("\n\n"):
if len(pkg_txt) == 0:
continue
pkg_lines = pkg_txt.split("\n")
date, name = pkg_lines[0].split(" >>> ")
time = parse_time(pkg_lines[1])
date = datetime.strptime(date, "%a %b %d %H:%M:%S %Y")
pkg = CompiledPackage(name, date, time)
packages.append(pkg)
return packages
def get_compile_time(package_amount: int) -> int:
"""Get compilation time of last n specified packages (seconds)"""
packages = get_packages()
last_packages = packages[-package_amount:]
return sum(package.compile_time for package in last_packages)
if __name__ == "__main__":
try:
package_amt = int(sys.argv[1])
except IndexError:
print("Missing required argument: package amount")
except TypeError:
print("Argument must be a number (package amount)")
else:
time = get_compile_time(package_amt)
print(get_readable_duration(time))

63
home/.local/bin/screenshot Executable file
View file

@ -0,0 +1,63 @@
#!/bin/bash
format="Screenshot_%Y%m%d_%H%M%S.png"
destination="~/Pictures/Screenshots/"
clipboard=0
xmonad=0
POSITIONAL=()
while [[ $# -gt 0 ]] ;do
key=$1
case $key in
-c|--clipboard)
clipboard=1
shift
;;
--xmonad)
xmonad=1
shift
;;
-f|--format)
format=$2
shift
shift
;;
-d|--destination)
destination=$2
shift
shift
;;
-e|--exec)
echo "Can't use exec, already used by script"
exit 1
;;
*)
POSITIONAL+=("$1")
shift
;;
esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters
# Define the base command
cmd="scrot '$format'"
# Handle exec arg for img destination (clipboard/folder)
if [ $clipboard -eq 1 ]; then
cmd+=" -e 'xclip -selection clipboard -t image/png -i \$f && rm \$f'"
else
cmd+=" -e 'mv \$f $destination'"
fi
# For some reason, xmonad can't run this without first sleeping
if [ $xmonad -eq 1 ]; then
cmd="sleep 0.2; $cmd"
fi
# Add user-defined arguments
cmd+=" $@"
# Execute the string command
eval $cmd

30
home/.local/bin/setbg Executable file
View file

@ -0,0 +1,30 @@
#!/bin/sh
# This script does the following:
# Run by itself, set the wallpaper
# If given a file, set that as the new wallpaper
# If given a directory, recursively choose a random file in it.
# Location of the symlink to wallpaper image
bgloc="${XDG_DATA_HOME:-$HOME/.local/share}/background"
trueloc="$(readlink -f "$1")" &&
case "$(file --mime-type -b "$trueloc")" in
image/* )
ln -sf "$(readlink -f "$1")" "$bgloc"
notify-send -i "$bgloc" "Changing wallpaper..."
;;
inode/directory )
randimg="$(find -L $trueloc -iregex '.*.\(jpg\|jpeg\|png\|gif\)' -type f | shuf -n 1)"
echo $randimg
ln -sf "$randimg" "$bgloc"
notify-send -i "$bgloc" "Random Wallpaper chosen."
;;
*)
notify-send "Error" "Not a valid image."
exit 1
;;
esac
# Use xwallpaper to set the background
xwallpaper --zoom "$bgloc"