about summary refs log tree commit diff stats
path: root/dot_local/bin
diff options
context:
space:
mode:
authorVitor Gonçalves <vitorg@tilde.team>2023-05-21 06:34:37 -0300
committerVitor Gonçalves <vitorg@tilde.team>2023-05-21 06:34:37 -0300
commit6a41699d952cb4116603539420353b4225d8c1d0 (patch)
tree4032b559d694454d49104cdcb3bf2542eedd3973 /dot_local/bin
downloaddots-6a41699d952cb4116603539420353b4225d8c1d0.tar.gz
Initial commit
Diffstat (limited to 'dot_local/bin')
-rw-r--r--dot_local/bin/executable_0174
-rw-r--r--dot_local/bin/executable_gg6
-rw-r--r--dot_local/bin/executable_pass2csv308
-rw-r--r--dot_local/bin/executable_pip8
-rw-r--r--dot_local/bin/executable_pip38
-rw-r--r--dot_local/bin/executable_pip3.118
-rw-r--r--dot_local/bin/executable_s44
-rw-r--r--dot_local/bin/executable_screenshotit4
-rw-r--r--dot_local/bin/executable_shorten-clipb3
-rw-r--r--dot_local/bin/executable_wal13
-rw-r--r--dot_local/bin/executable_xb28
11 files changed, 604 insertions, 0 deletions
diff --git a/dot_local/bin/executable_0 b/dot_local/bin/executable_0
new file mode 100644
index 0000000..95cab51
--- /dev/null
+++ b/dot_local/bin/executable_0
@@ -0,0 +1,174 @@
+#!/bin/sh
+
+# init variables
+version="v2022.11.03"
+ENDPOINT="https://0.vern.cc"
+flag_options=":hvcfe:s:"
+long_flag_options="help,version,color,file,extension:,server:"
+flag_version=0
+flag_help=0
+flag_file=0
+flag_colors=0
+flag_ext=0
+data=""
+EXT=""
+
+# help message available via func
+show_help() {
+  cat > /dev/stdout << END
+pb [options] filename
+or
+(command-with-stdout) | pb
+
+Uploads a file or data to the tilde 0x0 paste bin
+
+OPTIONAL FLAGS:
+  -h | --help)                    Show this help
+  -v | --version)                 Show current version number
+  -f | --file)                    Explicitly interpret stdin as filename
+  -c | --color)                   Pretty color output
+  -s | --server server_address)   Use alternative pastebin server address
+  -e | --extension bin_extension) Specify file extension used in the upload
+END
+}
+
+show_usage() {
+  cat > /dev/stdout << END
+usage: pb [-hfvcux] [-s server_address] filename
+END
+}
+
+# helper for program exit, supports error codes and messages
+die () {
+  msg="$1"
+  code="$2"
+  # exit code defaults to 1
+  if printf "%s" "${code}" | grep -q '^[0-9]+$'; then
+    code=1
+  fi
+  # output message to stdout or stderr based on code
+  if [ -n "${msg}" ]; then
+    if [ "${code}" -eq 0 ]; then
+      printf "%s\\n" "${msg}"
+    else
+      printf "%s%s%s\\n" "$ERROR" "${msg}" "$RESET" >&2
+    fi
+  fi
+  exit "${code}"
+}
+
+# attempt to parse options or die
+if ! PARSED_ARGUMENTS=$(getopt -a -n pb -o ${flag_options} --long ${long_flag_options} -- "$@"); then
+  printf "pb: unknown option\\n"
+  show_usage
+  exit 2
+fi
+
+# For debugging: echo "PARSED_ARGUMENTS is $PARSED_ARGUMENTS"
+eval set -- "$PARSED_ARGUMENTS"
+while :
+do
+  case "$1" in
+    -h | --help)      flag_help=1                  ; shift   ;;
+    -v | --version)   flag_version=1               ; shift   ;;
+    -c | --color)     flag_color=1                 ; shift   ;;
+    -f | --file)      flag_file=1                  ; shift   ;;
+    -e | --extension) flag_ext=1;    EXT="$2"      ; shift 2 ;;
+    -s | --server)                   ENDPOINT="$2" ; shift 2 ;;
+    --) shift; break ;;
+    *) echo "Unexpected option: $1 - this should not happen."
+       show_usage ; die 3 ;;
+  esac
+done
+
+# display current version
+if [ ${flag_version} -gt 0 ]; then
+  printf "%s\\n" "${version}"
+  die "" 0
+fi
+
+# display help
+if [ ${flag_help} -gt 0 ]; then
+  show_help
+  die "" 0
+fi
+
+# is not interactive shell, use stdin
+if [ -t 0 ]; then
+  flag_file=1
+else
+  if [ ${flag_ext} -gt 0 ]; then
+    # short-circuit stdin access to ensure binary data is transferred to curl
+    curl -sF"file=@-;filename=null.${EXT}" "${ENDPOINT}" < /dev/stdin
+    exit 0
+  else
+    data="$(cat < /dev/stdin )"
+  fi
+fi
+
+# if data variable is empty (not a pipe) use params as fallback
+if [ -z "$data" ]; then
+  data="$*"
+fi
+
+# Colors
+if [ ${flag_colors} -gt 0 ]; then
+  SUCCESS=$(tput setaf 190)
+  ERROR=$(tput setaf 196)
+  RESET=$(tput sgr0)
+else
+  SUCCESS=""
+  ERROR=""
+  RESET=""
+fi
+
+if [ ${flag_file} -gt 0 ]; then
+  # file mode
+  if [ -z "${data}" ]; then
+    # if no data
+    # print error message
+    printf "%sProvide data to upload%s\\n" "$ERROR" "$RESET"
+  elif [ ! -f "${data}" ]; then
+    # file not found with name provided
+    # print error messagse
+    printf "%s%s%s\\tFile not found.%s\\n" "$RESET" "${data}" "$ERROR" "$RESET"
+    # attempt to split data string (multi-line?) and upload each string as file
+    for f in ${data}; do
+      # if there's nothing to parse, skip this loop
+      if [ "$f" = "$data" ]; then
+        break;
+      fi
+      # check if file exists
+      if [ -f "${f}" ]; then
+        if [ ${flag_ext} -gt 0 ]; then
+          # send file to endpoint masked with new extension
+          result=$(curl -sF"file=@${f};filename=null.${EXT}" "${ENDPOINT}")
+        else
+          # send file to endpoint
+          result=$(curl -sF"file=@${f}" "${ENDPOINT}")
+        fi
+        printf "%s%s%s\\n" "$SUCCESS" "$result" "$RESET"
+      else
+        # print error message
+        printf "%sFile not found.%s\\n" "$ERROR" "$RESET"
+      fi
+    done
+  else
+    # data available in file
+    # send file to endpoint
+    result=$(curl -sF"file=@${data}" "${ENDPOINT}")
+    printf "%s%s%s\\n" "$SUCCESS" "$result" "$RESET"
+  fi
+else
+  # non-file mode
+  if [ -z "${data}" ]; then
+    # if no data
+    # print error message
+    printf "%sNo data found for upload. Please try again.%s\\n" "$ERROR" "$RESET"
+  else
+    # data available
+    # send data to endpoint
+    result=$(printf "%s" "${data}" | curl -sF"file=@-;filename=null.txt" "${ENDPOINT}")
+    printf "%s%s%s\\n" "$SUCCESS" "$result" "$RESET"
+  fi
+fi
diff --git a/dot_local/bin/executable_gg b/dot_local/bin/executable_gg
new file mode 100644
index 0000000..a8a2150
--- /dev/null
+++ b/dot_local/bin/executable_gg
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+
+POSTDATE="$(date '+%Y-%m-%d %H:%M %:::z')\n\n"
+
+$EDITOR /tmp/gemlog-post.txt && sed -i "2s\`^.*$\`\n## $POSTDATE$(cat /tmp/gemlog-post.txt)\n\n-----\n\`" "$HOME/docs/src/gmi/tinylog.gmi"
+cd "$HOME"/docs/src/gmi/; git diff
diff --git a/dot_local/bin/executable_pass2csv b/dot_local/bin/executable_pass2csv
new file mode 100644
index 0000000..d4af0f9
--- /dev/null
+++ b/dot_local/bin/executable_pass2csv
@@ -0,0 +1,308 @@
+#!/bin/python
+import argparse
+import csv
+import logging
+import pathlib
+import re
+import sys
+
+import gnupg
+
+logging.basicConfig(level=logging.INFO, format='%(message)s')
+
+
+def set_meta(entry, path, grouping_base):
+    pure_path = pathlib.PurePath(path)
+    group = pure_path.relative_to(grouping_base).parent
+    if group.name == '':
+        group = ''
+    entry['group'] = group
+    entry['title'] = pure_path.stem
+
+
+def set_data(entry, data, exclude, get_fields, get_lines):
+    lines = data.splitlines()
+    tail = lines[1:]
+    entry['password'] = lines[0]
+
+    filtered_tail = []
+    for line in tail:
+        for exclude_pattern in exclude:
+            if exclude_pattern.search(line):
+                break
+        else:
+            filtered_tail.append(line)
+
+    matching_indices = set()
+    fields = entry.setdefault('fields', {})
+
+    for i, line in enumerate(filtered_tail):
+        for name, pattern in get_fields:
+            if name in fields:
+                # multiple patterns with same name, we've already found a match
+                continue
+            match = pattern.search(line)
+            if not match:
+                continue
+            inverse_match = line[0:match.start()] + line[match.end():]
+            value = inverse_match.strip()
+            fields[name] = value
+            matching_indices.add(i)
+            break
+
+    matching_lines = {}
+    for i, line in enumerate(filtered_tail):
+        for name, pattern in get_lines:
+            match = pattern.search(line)
+            if not match:
+                continue
+            matches = matching_lines.setdefault(name, [])
+            matches.append(line)
+            matching_indices.add(i)
+            break
+    for name, matches in matching_lines.items():
+        fields[name] = '\n'.join(matches)
+
+    final_tail = []
+    for i, line in enumerate(filtered_tail):
+        if i not in matching_indices:
+            final_tail.append(line)
+
+    entry['notes'] = '\n'.join(final_tail).strip()
+
+
+def write(file, entries, get_fields, get_lines):
+    get_field_names = set(x[0] for x in get_fields)
+    get_line_names = set(x[0] for x in get_lines)
+    field_names = get_field_names | get_line_names
+    header = ["Group(/)", "Title", "Password", *field_names, "Notes"]
+    csvw = csv.writer(file)
+    logging.info("\nWriting data to %s\n", file.name)
+    csvw.writerow(header)
+    for entry in entries:
+        fields = [entry['fields'].get(name) for name in field_names]
+        columns = [
+            entry['group'], entry['title'], entry['password'],
+            *fields,
+            entry['notes']
+        ]
+        csvw.writerow(columns)
+
+
+def main(store_path, outfile, grouping_base, gpgbinary, use_agent, encodings,
+         exclude, get_fields, get_lines):
+    entries = []
+    failures = []
+    path = pathlib.Path(store_path)
+    grouping_path = pathlib.Path(grouping_base)
+    gpg = gnupg.GPG(gpgbinary=gpgbinary, use_agent=use_agent)
+    files = path.glob('**/*.gpg')
+    if not path.is_dir():
+        if path.is_file():
+            files = [path]
+        else:
+            err = "No such file or directory: {}".format(path)
+            logging.error(err)
+            sys.exit(1)
+    for file in files:
+        logging.info("Processing %s", file)
+        with open(file, 'rb') as fp:
+            decrypted = gpg.decrypt_file(fp)
+        if not decrypted.ok:
+            err = "Could not decrypt {}: {}".format(file, decrypted.status)
+            logging.error(err)
+            failures.append(err)
+            continue
+        for i, encoding in enumerate(encodings):
+            try:
+                # decrypted.data is bytes
+                decrypted_data = decrypted.data.decode(encoding)
+            except Exception as e:
+                logging.warning(
+                    "Could not decode {} with encoding {}: {}"
+                    .format(file, encoding, e)
+                )
+                continue
+            if i > 0:
+                # don't log if the first encoding worked
+                logging.warning("Decoded {} with encoding {}".format(file, encoding))
+            break
+        else:
+            err = "Could not decode {}, see messages above for more info.".format(file)
+            failures.append(err)
+            continue
+        entry = {}
+        set_meta(entry, file, grouping_path)
+        set_data(entry, decrypted_data, exclude, get_fields, get_lines)
+        entries.append(entry)
+    if failures:
+        logging.warning("\nGot errors while processing files:")
+        for err in failures:
+            logging.warning(err)
+    write(outfile, entries, get_fields, get_lines)
+
+
+def parse_args(args=None):
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        'store_path',
+        metavar='STOREPATH',
+        type=str,
+        help="path to the password-store to export",
+    )
+
+    parser.add_argument(
+        'outfile',
+        metavar='OUTFILE',
+        type=argparse.FileType('w'),
+        help="file to write exported data to, use - for stdout",
+    )
+
+    parser.add_argument(
+        '-b', '--base',
+        metavar='path',
+        type=str,
+        help="path to use as base for grouping passwords",
+        dest='base_path'
+    )
+
+    parser.add_argument(
+        '-g', '--gpg',
+        metavar='executable',
+        type=str,
+        default="gpg",
+        help="path to the gpg binary you wish to use (default 'gpg')",
+        dest='gpgbinary'
+    )
+
+    parser.add_argument(
+        '-a', '--use-agent',
+        action='store_true',
+        default=False,
+        help="ask gpg to use its auth agent",
+        dest='use_agent'
+    )
+
+    parser.add_argument(
+        '--encodings',
+        metavar='encodings',
+        type=str,
+        default="utf-8",
+        help=(
+            "comma-separated text encodings to try, in order, when decoding"
+            " gpg output (default 'utf-8')"
+        ),
+        dest='encodings'
+    )
+
+    parser.add_argument(
+        '-e', '--exclude',
+        metavar='pattern',
+        action='append',
+        type=str,
+        default=[],
+        help=(
+            "regexp for lines which should not be exported, can be specified"
+            " multiple times"
+        ),
+        dest='exclude'
+    )
+
+    parser.add_argument(
+        '-f', '--get-field',
+        metavar=('name', 'pattern'),
+        action='append',
+        nargs=2,
+        type=str,
+        default=[],
+        help=(
+            "a name and a regexp, the part of the line matching the regexp"
+            " will be removed and the remaining line will be added to a field"
+            " with the chosen name. only one match per password, matching"
+            " stops after the first match"
+        ),
+        dest='get_fields'
+    )
+
+    parser.add_argument(
+        '-l', '--get-line',
+        metavar=('name', 'pattern'),
+        action='append',
+        nargs=2,
+        type=str,
+        default=[],
+        help=(
+            "a name and a regexp for which all lines that match are included"
+            " in a field with the chosen name"
+        ),
+        dest='get_lines'
+    )
+
+    return parser.parse_args(args)
+
+
+def compile_regexp(pattern):
+    try:
+        regexp = re.compile(pattern, re.I)
+    except re.error as e:
+        logging.error(
+            "Could not compile pattern '%s', %s at position %s",
+            pattern.replace("'", "\\'"), e.msg, e.pos
+        )
+        return None
+    return regexp
+
+
+if __name__ == '__main__':
+    parsed = parse_args()
+
+    failed = False
+    exclude_patterns = []
+    for pattern in parsed.exclude:
+        regexp = compile_regexp(pattern)
+        if not regexp:
+            failed = True
+        exclude_patterns.append(regexp)
+
+    get_fields = []
+    for name, pattern in parsed.get_fields:
+        regexp = compile_regexp(pattern)
+        if not regexp:
+            failed = True
+        get_fields.append((name, regexp))
+
+    get_lines = []
+    for name, pattern in parsed.get_lines:
+        regexp = compile_regexp(pattern)
+        if not regexp:
+            failed = True
+        get_lines.append((name, regexp))
+
+    if failed:
+        sys.exit(1)
+
+    if parsed.base_path:
+        grouping_base = parsed.base_path
+    else:
+        grouping_base = parsed.store_path
+
+    encodings = [e for e in parsed.encodings.split(',') if e]
+    if not encodings:
+        logging.error(
+            "Did not understand '--encodings {}'".format(parsed.encoding)
+        )
+        sys.exit(1)
+
+    kwargs = {
+        'store_path': parsed.store_path,
+        'outfile': parsed.outfile,
+        'grouping_base': grouping_base,
+        'gpgbinary': parsed.gpgbinary,
+        'use_agent': parsed.use_agent,
+        'encodings': encodings,
+        'exclude': exclude_patterns,
+        'get_fields': get_fields,
+        'get_lines': get_lines
+    }
+
+    main(**kwargs)
diff --git a/dot_local/bin/executable_pip b/dot_local/bin/executable_pip
new file mode 100644
index 0000000..6443bcd
--- /dev/null
+++ b/dot_local/bin/executable_pip
@@ -0,0 +1,8 @@
+#!/bin/python
+# -*- coding: utf-8 -*-
+import re
+import sys
+from pip._internal.cli.main import main
+if __name__ == '__main__':
+    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
+    sys.exit(main())
diff --git a/dot_local/bin/executable_pip3 b/dot_local/bin/executable_pip3
new file mode 100644
index 0000000..6443bcd
--- /dev/null
+++ b/dot_local/bin/executable_pip3
@@ -0,0 +1,8 @@
+#!/bin/python
+# -*- coding: utf-8 -*-
+import re
+import sys
+from pip._internal.cli.main import main
+if __name__ == '__main__':
+    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
+    sys.exit(main())
diff --git a/dot_local/bin/executable_pip3.11 b/dot_local/bin/executable_pip3.11
new file mode 100644
index 0000000..6443bcd
--- /dev/null
+++ b/dot_local/bin/executable_pip3.11
@@ -0,0 +1,8 @@
+#!/bin/python
+# -*- coding: utf-8 -*-
+import re
+import sys
+from pip._internal.cli.main import main
+if __name__ == '__main__':
+    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
+    sys.exit(main())
diff --git a/dot_local/bin/executable_s b/dot_local/bin/executable_s
new file mode 100644
index 0000000..e222ea7
--- /dev/null
+++ b/dot_local/bin/executable_s
@@ -0,0 +1,44 @@
+#!/usr/bin/env bash
+case $1 in
+	cf)
+		filename="$(date '+%d_%m_%Y-%H_%M_%s').png"
+		maim -s > "$HOME/media/screenshots/$filename"
+		xclip -sel clipb -t image/png "$HOME/media/screenshots/$filename"
+		;;
+	cl)
+		filename="$(date '+%d_%m_%Y-%H_%M_%s').png"
+		maim -s > $HOME/media/screenshots/$filename
+		curl -F"file=@$HOME/media/screenshots/$filename" -Fsecret= "https://0.vern.cc/" | xclip -sel clipb
+		;;
+	wf)
+		filename="$(date '+%d_%m_%Y-%H_%M_%s').png"
+		maim -i $(xdotool getactivewindow) > "$HOME/media/screenshots/$filename"
+		xclip -sel clipb -t image/png "$HOME/media/screenshots/$filename"
+		;;
+	wl)
+		filename="$(date '+%d_%m_%Y-%H_%M_%s').png"
+		maim -i $(xdotool getactivewindow) > $HOME/media/screenshots/$filename
+		curl -F"file=@$HOME/media/screenshots/$filename" -Fsecret= "https://0.vern.cc/" | xclip -sel clipb
+		;;
+	ff)
+		filename="$(date '+%d_%m_%Y-%H_%M_%s').png"
+		maim > "$HOME/media/screenshots/$filename"
+		xclip -sel clipb -t image/png "$HOME/media/screenshots/$filename" 
+		;;
+	fl)
+		filename="$(date '+%d_%m_%Y-%H_%M_%s').png"
+		maim > $HOME/media/screenshots/$filename
+		curl -F"file=@$HOME/media/screenshots/$filename" -Fsecret= "https://0.vern.cc/" | xclip -sel clipb
+		;;
+	*)
+		echo "Usage info:"
+		echo
+		echo "s cf - Takes a screenshot from a region and then copies the file to the clipboard selection"
+		echo "s cl - Takes a screenshot from a region and then uploads it to 0.vern.cc, and automatically copies the link"
+		echo "s wf - Takes a screenshot from the active window and then copies the file to the clipboard selection"
+		echo "s wl - Takes a screenshot from the active window and then uploads it to 0.vern.cc, and automatically copies the link"
+		echo "s ff - Takes a screenshot of the full screen and then copies the file to the clipboard selection"
+		echo "s fl - Takes a screenshot of the full screen and then uploads it to 0.vern.cc, and automatically copies the link"
+		echo 
+		echo "Notice: all of these commands output it's screenshots to \`~/media/screenshots/\`."
+esac
diff --git a/dot_local/bin/executable_screenshotit b/dot_local/bin/executable_screenshotit
new file mode 100644
index 0000000..5808b4a
--- /dev/null
+++ b/dot_local/bin/executable_screenshotit
@@ -0,0 +1,4 @@
+#!/usr/bin/env bash
+
+printf "Fullscreen, copy file (ff)\nFullscreen, copy link (fl)\nWindow, copy file (wf)\nWindow, copy link (wl)\nRegion, copy file (rf)\nRegion, copy link (rl)" | dmenu -l 6 |\
+	sed "s/Fullscreen/f/;s/Window/w/;s/Region/c/;s/copy file/f/;s/copy link/l/;s/, //" | xargs "s"
diff --git a/dot_local/bin/executable_shorten-clipb b/dot_local/bin/executable_shorten-clipb
new file mode 100644
index 0000000..c17abab
--- /dev/null
+++ b/dot_local/bin/executable_shorten-clipb
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+
+curl -F"shorten=$(xclip -o)" -Fsecret= https://0.vern.cc/ | xclip -sel clipb
diff --git a/dot_local/bin/executable_wal b/dot_local/bin/executable_wal
new file mode 100644
index 0000000..628f81f
--- /dev/null
+++ b/dot_local/bin/executable_wal
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+
+WALLPAPER_DIR="$HOME/media/wallpapers"
+
+case $1 in
+    r)
+        find $WALLPAPER_DIR -iname "*.jpg" | shuf -n 1 | xargs xwallpaper --stretch
+        ;;
+    *)
+        echo "Usage info:"
+        ;;
+esac
+
diff --git a/dot_local/bin/executable_xb b/dot_local/bin/executable_xb
new file mode 100644
index 0000000..c83e670
--- /dev/null
+++ b/dot_local/bin/executable_xb
@@ -0,0 +1,28 @@
+#!/usr/bin/env bash
+case $1 in
+    install | i | add)
+        sudo xbps-install ${@:2}
+        ;;
+    remove | r | del | delete)
+        sudo xbps-remove ${@:2}
+        ;;
+    query | q | search | s)
+        sudo xbps-query ${@:2}
+        ;;
+    upgrade | u)
+        sudo xbps-install -Su
+        ;;
+    locate | l | find | f)
+        xlocate ${@:2}
+        ;;
+    *)
+        echo "Usage info:"
+        echo
+        echo "xb i - Calls 'sudo xbps-install' with the following arguments"
+        echo "xb q - Calls 'sudo xbps-query' with the following arguments"
+        echo "xb r - Calls 'sudo xbps-remove' with the following arguments"
+        echo "xb u - Upgrades the system packages with 'sudo xbps-install -Su'"
+        echo "xb l - Pass following arguments to xlocate"
+        echo "xb h - Displays help"
+        ;;
+esac