scripts

shell scripts
git clone git://git.bitsmanent.org/scripts
Log | Files | Refs | README

README.md (14507B)


      1 scripts
      2 =======
      3 Useful shell scripts.
      4 
      5 index
      6 -----
      7 * [txthole](#txthole) - Simple netcat-based pastebin server (also see [beans](https://git.bitsmanent.org/beans/log.html))
      8 * [iwpick](#iwpick) - Connects to a network.
      9 * [scrapthumb](#scrapthumb) - Get random images from Tumblr.
     10 * [acpi](#acpi) - Simple power management.
     11 * [dwmstatus](#dwmstatus) - Output useful informations suitable for a status bar.
     12 * [spawncgi](#spawncgi) - Spawn the CGI daemon.
     13 * [pronunciask](#pronunciask) - Get pronunciations from forvo.com.
     14 * [pkgsetup](#pkgsetup) - Easy pkgsrc (and -wip) for non-NetBSD systems.
     15 * [whexsafe](#whexsafe) - Web safe color list in hex and RGB.
     16 * [swss](#swss) - Start/stop a group of services.
     17 * [droid](#droid) - Sane Android development. *deprecated*.
     18 * [dbrowse](#dbrowse) - Little dmenu-based file browser.
     19 * [diffmon](#diffmon) - Diff-based file monitor.
     20 * [sober](#sober) - Simple sobriety checker.
     21 * [mkbkp](#mkbkp) - Simple backups.
     22 * [setmon](#setmon) - Switch to HDMI video/audio if any.
     23 * [moin](#moin) - Play a random song from a YouTube playlist.
     24 * [fetchpic](#fetchpic) - Fetch a random pic from a random blog (of a given list).
     25 * [sendpush](#sendpush) - Send a PUSH notification via xdroid API
     26 * [wally](#wally) - Change random wallpapers taken from the web
     27 
     28 txthole
     29 -------
     30 Store and retrieve text stream. Superseded by
     31 [beans](//git.bitsmanent.org/beans/log.html). Given the script is up and
     32 running, here's a sample usage:
     33 
     34 	$ echo Hello |nc your.host 2023
     35 	http://your.host/GmKwL
     36 	echo GmKwL |nc your.host 2023
     37 	$ echo GmKwL |nc your.host 2023
     38 	Hello
     39 
     40 Of course you can also paste files:
     41 
     42 	$ cat /tmp/t |nc your.host 2023
     43 
     44 You can set hostname when starting txthole, like this:
     45 
     46 	$ TXTHOLE_PUBHOST=my.public.host txthole &
     47 
     48 If it's unset then txthole will only output the code instead of the whole command:
     49 
     50 	$ txthole &
     51 	$ echo Hello |nc your.host 2023
     52 	A1Syh
     53 
     54 This should be enough for most use cases.
     55 
     56 To serve content over HTTP, use something like this (nginx):
     57 
     58 	server {
     59 		root /tmp/pastes/;
     60 		server_name your.host;
     61 		index txthole.index.paste;
     62 
     63 		location / {
     64 			rewrite ^/([-.a-zA-Z0-9]+)$ "/txthole.$1.paste" last;
     65 		}
     66 
     67 		location ~ \.paste$ {
     68 			add_header Content-Type text/plain;
     69 		}
     70 	}
     71 
     72 Take care of applying the right user/permission to the pastes directory:
     73 
     74 	# chgrp www-data /tmp/pastes
     75 	# chmod g+srx /tmp/pastes # s used to keep group
     76 
     77 
     78 iwpick
     79 ------
     80 Connects to a network. Authentication is not mandatory and only WPA2 is supported at the moment. It will works with no pain on any Linux system equipped with iwconfig, sdhcp and wpa_supplicant. Just run:
     81 
     82 	$ sudo iwpick -e MyWirelessNetwork -k MyWPA2key
     83 
     84 You may also use an aliases file (default ~/.networks), like this:
     85 
     86 	home:MyHomeNetwork:MyHomePassword
     87 	lucky:PublicNetwork
     88 	
     89 Then use the alias to connect:
     90 
     91 	$ sudo iwpick -a home
     92 
     93 Connect to the first known network available:
     94 
     95 	$ sudo iwpick -p
     96 
     97 *TIP: $ chmod og-rwx ~/.networks*
     98 
     99 I'm considering if implement or not a flag to connects to the best possible network. The priority should be, descending order: private known networks, public known networks, public unknown networks. Networks with higher security and/or signal have higher priority. For now it's just an idea.
    100 
    101 **Known issues**
    102 - [sdhcp](http://git.2f30.org/sdhcp/) may wait forever if the network interface don't have an IP address assigned. The workaround is to assign an IP address to the interface before run iwpick. Note: the address must be a valid IP for the network; this may be changed by sdhcp.
    103 - The `/etc/resolv.conf` is not update by iwpick so you'll have to put your nameservers there by hand. Alternatively, you can edit the iwpick script and remove the -d flag for sdhcp.
    104 
    105 scrapthumb
    106 ----------
    107 Get random images from Tumblr.  
    108 
    109 Note: currently not working due to the recent Tumblr redirect to the new
    110 privacy policy, which you need to accept.
    111 
    112 Some sample usages in ~/.xinitrc:
    113 
    114 	# Change wallpaper each 5 minutes 
    115 	while true; do
    116 		feh --bg-max $(/path/of/scrapthumb -rn1)
    117 		sleep 5m
    118 	done &
    119 
    120 	# Change wallpaper each 5 minutes by storing the source into
    121 	# /tmp/.scrapthumb (new with the -u flag)
    122 	while true; do
    123 		t="$(/path/of/scrapthumb -urn1)"
    124 		src=$(echo $t |cut -d'|' -f1)
    125 		img=$(echo $t |cut -d'|' -f2)
    126 		feh --no-fehbg --bg-fill "$img"
    127 		echo "$t" > /tmp/.scrapthumb
    128 
    129 		sleep 5m
    130 	done &
    131 
    132 If the image is in GIF format then the first frame is used (i.e. no playing at
    133 all). You can solve this by splitting frames up with convert(1) and set each of
    134 them as background with an interval of ~0.01 seconds. A better approach would
    135 be to use mpv with the --wid=0 parameter which is less CPU intensive.
    136 
    137 You can achieve more extreme results by using scrapthumb in conjunction with
    138 semi-automatic customization tools. Have a look at
    139 [autotheme.sh](https://github.com/neeasade/autotheme.sh).
    140 
    141 acpi
    142 ----
    143 Notice the user if the battery charge is below 12% or suspend (in memory) the
    144 system if the battery is below 9%. Make it runs each minute via cron like this:
    145 ```
    146 * * * * * sudo -i /path/of/acpi
    147 ```
    148 
    149 It uses xmessage(1) and play(1) to alert the user.
    150 
    151 dwmstatus
    152 ---------
    153 Output useful informations suitable for a status bar. It's designed for dwm.
    154 Obsolete: use [slstatus](https://tools.suckless.org/slstatus/) instead.
    155 
    156 Sample output:
    157 ```
    158 B:89%+ T:56C W:70% V:95%  (0.23 0.21 0.22 0.16) 25/09/2015 11:15
    159 ```
    160 
    161 Here is a brief explanations of the fields:
    162 
    163 - B: battery percentage. A trailing symbol indicates that AC power is plugged (+) or not (-)
    164 - T: temperature in celsius degrees
    165 - W: wireless signal
    166 - V: volume. A trailing asterisk indicates if the mute is on
    167 - Load average between parenthesis
    168 - Date and time
    169 
    170 To set the dwm bar you have to call xsetroot, like this:
    171 ```
    172 xsetroot -name "$(/path/of/dwmstatus)"
    173 ```
    174 
    175 It's easy to auto-update the bar by putting this in your ~/.xinitrc:
    176 ```
    177 while true; do
    178 	xsetroot -name "$(/path/of/dwmstatus)"
    179 	sleep 30s
    180 done &
    181 ```
    182 
    183 spawncgi
    184 --------
    185 Spawn the CGI daemon.
    186 
    187 pronunciask
    188 -----------
    189 Get pronunciations from forvo.com. Written for fun.
    190 
    191 pkgsetup
    192 --------
    193 Managing pkgsrc bootstrapping and installation on non-NetBSD systems. Also
    194 supports pkgsrc-wip.
    195 
    196 whexsafe
    197 --------
    198 Generates the web safe colors list in hex and RGB formats.
    199 
    200 swss
    201 ----
    202 Simple web stack switch. It just tiny script to start and stop a group of
    203 services which I use to deal with my web stack (redis, mysql, nginx, etc.).
    204 
    205 droid
    206 -----
    207 Sane Android Development.
    208 Note: this script is deprecated, see below.
    209 
    210 ```
    211 $ droid
    212 Usage: droid <cmd>
    213 
    214 Commands:
    215    setup        : creates the development environment
    216    install      : install the app into the device
    217    upload       : upload the app into the device
    218    build        : build the app (if no task, assumes assembleDebug)
    219    upgrade      : build and install the app (assembleDebug)
    220    deploy       : build and install the app (assembleRelease)
    221    init         : create a new project into the current directory
    222    clean        : remove all builds
    223    help         : print this help
    224 ```
    225 
    226 You can now achieve the same results using the great
    227 [sdkmanager](https://developer.android.com/studio/command-line/sdkmanager) tool
    228 along with [gradle](https://gradle.org/releases/) on the command line. In fact,
    229 I started to use those tools and I will not work on droid anymore.
    230 
    231 
    232 dbrowse
    233 ------
    234 Little dmenu-based file browser which output the selected files (if any).
    235 
    236 Sample usage (for a single file):
    237 
    238 ```
    239 $ mimeopen "$(/path/of/dbrowse)"
    240 ```
    241 
    242 For [dwm](http://dwm.suckless.org) users, it may come in handy a key binding
    243 like this:
    244 
    245 ```
    246 { MODKEY|ShiftMask,		XK_o,      spawn,          SHCMD("mimeopen -n \"$(/path/of/dbrowse)\"") },
    247 ```
    248 
    249 Multiple selections are also supported.
    250 
    251 
    252 diffmon
    253 -------
    254 Simple script which monitor a file and show lines that are changed since you
    255 ran it.
    256 
    257 sober
    258 -----
    259 Simple sobriety checker inspired by [DrunkGuard](https://github.com/jkingsman/DrunkGuard).
    260 
    261 In a nutshell:
    262 ```
    263 $ sudo rm -rf /
    264 How much is 7 + 1? 8
    265 How much is 5 + 9? 12
    266 You're drunk, I'll take care of you.
    267 ```
    268 
    269 Use sober by creating aliases in your ~/.${SHELL}rc file:
    270 
    271 ```
    272 alias sudo="/path/of/sober sudo"
    273 alias rm="/path/of/sober rm"
    274 alias mv="/path/of/sober mv"
    275 alias apt-get="/path/of/sober apt-get"
    276 alias dpkg="/path/of/sober dpkg"
    277 ```
    278 
    279 You may want to toggle this aliases at specific times (e.g. after work hours).
    280 This is easily achievable with simple shell scripts.
    281 
    282 mkbkp
    283 -----
    284 Copy all tracked files and git repositories into a directory. The stuff to
    285 backup is taken from the file given as argument or ${HOME}/.mkbkprc if no
    286 argument is given.
    287 
    288 Sample configuration:
    289 ```
    290 # default destination path if not given
    291 BKPDIR="backup-$(hostname -s)-$(date +'%Y%m%d')"
    292 
    293 # files and directories
    294 NAMES="
    295 ${HOME}/myfiles
    296 ${HOME}/mail
    297 ${HOME}/.config/chromium/Default/Bookmarks
    298 "
    299 
    300 # git repositories
    301 GITREPOS="
    302 git@github.com:clamiax/scripts.git
    303 "
    304 
    305 onfinish() {
    306 	t="$1.tar.bz2"
    307 
    308 	echo -n "Compressing to $t..."
    309 	tar jcf "$t" "$1"
    310 	echo " done"
    311 
    312 	echo -n "Uploading to a backup server..."
    313 	scp "$t" user@host:/path/of/backup
    314 	echo " done"
    315 
    316 	echo "Completed."
    317 }
    318 ```
    319 
    320 mkbkp only supports backup of files, directories and git repositories. Though
    321 it easy to add support for virtually anything. Just declare a function in your
    322 configuration file and add its name into the $SUPPORT variable. See bkp_names
    323 and bkp_gitrepos in [mkbkp](src/mkbkp) to learn more.
    324 
    325 setmon
    326 ------
    327 Detects connected screens and set proper video and audio output. It uses xrandr
    328 and pulseaudio. I wrote it to easily switch forth and back from my HDMI TV.
    329 Change it to fit your needs.
    330 
    331 moin
    332 ----
    333 The [moin](src/moin) script takes a random song from the specified YouTube
    334 playlist and play it. The default player is mpv but you can refine the $PLAYER
    335 and $PLAYER_OPTS variables to fit your needs. You may want to wake up in the
    336 morning by putting the following in your crontab:
    337 
    338 ```
    339 # Plays from monday to friday at 08:00am
    340 0 8 * * 1-5 /path/of/moin <YOUR-API-KEY> <PLAYLIST-ID>
    341 ```
    342 
    343 Both the API key and the playlist ID are required. If you don't have a key then
    344 [make one here](https://console.developers.google.com/apis/credentials).
    345 The playlist ID is specified by the "list" parameter of the URL. For example,
    346 if the URL of your playlist is the following:
    347 
    348 ```
    349 https://www.youtube.com/watch?v=xvIuuKVwY_8&list=RDEMWmz07MSPRGna5rHl5FWPRw&index=40
    350 ```
    351 
    352 Then the ID is: RDEMWmz07MSPRGna5rHl5FWPRw
    353 
    354 fetchpic
    355 --------
    356 Fetch a random pic from a random blog (of a given list).
    357 
    358 This is [scrapthumb](#scrapthumb) rewritten from scratch and better. Now the
    359 Tumblr API is used so you need an [api key](https://www.tumblr.com/oauth/apps).
    360 
    361 In a nutshell:
    362 
    363 ```
    364 # scrap="$(APIKEY=Your-Api-Key fetchpic)"
    365 # uri="$(echo "$scrap" |cut -d'|' -f2)"
    366 # feh --bg-fill --no-fehbg "$uri"
    367 ```
    368 
    369 Put this in your `.xinitrc` to change the wallapaper each 5 minutes and append
    370 the pic URL and blog name into `/tmp/fetchpic`.
    371 
    372 ```
    373 while : ; do
    374 	scrap="$(APIKEY=Your-Api-Key fetchpic)"
    375 	uri="$(echo "$scrap" |cut -d' ' -f2)"
    376 	echo "$scrap" >> /tmp/fetchpic
    377 	feh --bg-fill --no-fehbg "$uri"
    378 	sleep 300
    379 done &
    380 ```
    381 
    382 Enjoy.
    383 
    384 sendpush
    385 --------
    386 Send a PUSH notification to your smartphone via xdroid API.
    387 
    388 ```
    389 $ sendpush -h
    390 sendpush -k <key> -t <title> -c <conten> [-u <uri>]
    391 ```
    392 
    393 Install the [app](https://play.google.com/store/apps/details?id=net.xdroid.pn) and you're done.
    394 
    395 wally
    396 -----
    397 Change random wallpapers taken from the web.
    398 
    399 Note: I do not use nor mantain `wally` anymore. Random images rotation is nice
    400 it but cannot always guarantee high quality results thus I decided to use a
    401 curated list of images from a Pexel collection with a script like
    402 [this](https://gist.github.com/bitsmanent/6ce604a5f09bd77b59fbbdf9dab818d1).
    403 
    404 ```
    405 $ wally -h
    406 Usage: wally [-h] -f <file>
    407 ```
    408 
    409 A configuration file is required to instruct `wally` about where to take
    410 images, how to filter them, how much wait for the next rotation, etc.
    411 
    412 Here is a sample file which support [Pexels](https://www.pexels.com) and
    413 [wttr](https://wttr.in/):
    414 
    415 ```
    416 # wally settings
    417 
    418 ENABLED_SERVICES="pexels wttr"
    419 DELAY=300
    420 LOGFILE="/tmp/wally.log"
    421 useresult() {
    422 	feh --bg-max --no-fehbg "$1"
    423 }
    424 
    425 ##
    426 # pexels
    427 # https://www.pexels.com/it-it/api/documentation
    428 ##
    429 pexels_apikey="your-api-key"
    430 pexels_opts="auto=compress&cs=tinysrgb&fit=crop&w=1920&h=1080"
    431 pexels_items="space:3000 rain:1000 sexy%20woman:10000 architecture:8000"
    432 pexels() {
    433 	nitems="$(obj_items "$pexels_items")"
    434 	index="$($(printf "$rand" 1 "$nitems"))"
    435 	item="$(obj_items "$pexels_items" "$index")"
    436 	query="$(echo -n "$item" |cut -d':' -f1)"
    437 	npages="$(echo -n "$item" |cut -d':' -f2)"
    438 	page="$($(printf "$rand" 1 "$npages"))"
    439 	qs="per_page=1&page=$page&query=$query"
    440 	uri="https://api.pexels.com/v1/search?$qs"
    441 	json="$(curl -sH "Authorization: $pexels_apikey" "$uri")"
    442 	original="$(echo "$json" |sed -n 's/.*"original":"\([^"]*\).*/\1/p')"
    443 
    444 	log "Pexels $query #$page $original"
    445 
    446 	[ "$npages" -gt 10000 ] && die "max pages is 10000 (current: $npages)"
    447 	[ -z "$original" ] && die "no results"
    448 	echo "$original?$pexels_opts"
    449 	return 0
    450 }
    451 
    452 ##
    453 # wttr
    454 # https://wttr.in/:help
    455 ##
    456 wttr_lang="it"
    457 wttr_items="_pF.png /moon_pF.png"
    458 wttr() {
    459 	nitems="$(obj_items "$wttr_items")"
    460 	index="$($(printf "$rand" 1 "$nitems"))"
    461 	item="$(obj_items "$wttr_items" "$index")"
    462 	uri="https://$wttr_lang.wttr.in${item}"
    463 
    464 	log "wttr $item $uri"
    465 	echo "$uri"
    466 	return 0
    467 }
    468 ```
    469 
    470 You can add any service you wish. Just create a function to fetch the random
    471 images and add its name into the `$ENABLED_SERVICES` variable. If you need to
    472 refine how the wallpaper is set you can also define a `_use` function which
    473 will be called instead of the default `useresult()`.
    474 
    475 A non-zero return value tell `wally` to write an error on the log file
    476 including any eventual output. It also prevent the `_use()` function to be
    477 called. The `die()` function may be used for convenience (see below).
    478 
    479 Actually, your function may produce any output (not necessarly an URL or a
    480 local filename) and inside `_use()` you may do anything you want without need
    481 to manage wallpapers at all.
    482 
    483 For instance, here is service to produce random numbers:
    484 
    485 ```
    486 rnum() {
    487 	n="$(shuf -n1 -i 10000-99999)"
    488 
    489 	# $n == 12345 throw an error
    490 	[ "$n" -eq 12345 ] && die "got exactly 12345"
    491 }
    492 
    493 rnum_use() {
    494 	xmessage -center "Random number: $1"
    495 }
    496 ```
    497 
    498 A few convenient functions are availables:
    499 
    500 - obj_items: count items in a list or return the given one
    501 - log: append the argument to `$LOGFILE`
    502 - die: print the argument and exit with code 1
    503 - d: print and log the argument
    504 
    505 See the `wally` script itself for details.