Script cleanup

This commit is contained in:
David Tomaschik
2026-07-06 15:59:12 -07:00
parent 22b3f2e049
commit da1ee162c2
13 changed files with 225 additions and 111 deletions

View File

@@ -4,7 +4,12 @@ set -ueo pipefail
shopt -s extglob
# get libraries
. ${HOME}/.local/lib/bash/tui.sh
if [[ -f "${HOME}/.local/lib/bash/tui.sh" ]]; then
. "${HOME}/.local/lib/bash/tui.sh"
else
echo "Error: ${HOME}/.local/lib/bash/tui.sh not found!" >&2
exit 1
fi
COMMANDS=(
gctx
@@ -43,7 +48,7 @@ _gctx_choose() {
--format='value(is_active, name, format("{} (as {})", properties.core.project, properties.core.account))')
local choice
if choice=$(printf "%-${maxnamelen}s %s\n" "${lines[@]}" | select_entry "gcloud config" "$default") ; then
_gctx_set "${choice}"
_gctx_set "$(echo "${choice}" | awk '{print $1}')"
else
echo "No option selected, leaving unchanged."
fi
@@ -68,7 +73,7 @@ _gctx_clone() {
local oldconfig=()
local line
while IFS= read -r line ; do
old_config+=("$line")
oldconfig+=("$line")
done < <(gcloud config configurations describe "$(_gctx_name)" --format='multi(properties:format="flattened[separator=\" \"]")')
# create new

View File

@@ -1,8 +1,22 @@
#!/bin/sh
env > ${TMPDIR}/env-pre
. ${HOME}/.shenv
env > ${TMPDIR}/env-post
for VAR in $(env | cut -d'=' -f1) ; do
/bin/launchctl setenv "${VAR}" "$(eval echo \$${VAR})"
done
set -o nounset
TMP_DIR="${TMPDIR:-/tmp}"
TMP_DIR="${TMP_DIR%/}"
env > "${TMP_DIR}/env-pre" 2>/dev/null || true
if [ -f "${HOME}/.shenv" ]; then
. "${HOME}/.shenv"
fi
env > "${TMP_DIR}/env-post" 2>/dev/null || true
if [ -x "/bin/launchctl" ]; then
for VAR in $(env | awk -F= '/^[a-zA-Z_][a-zA-Z0-9_]*=/ {print $1}') ; do
case "${VAR}" in
_|""|*[!a-zA-Z0-9_]*|[0-9]*) continue ;;
esac
eval "val=\${${VAR}:-}"
/bin/launchctl setenv "${VAR}" "${val}"
done
fi

View File

@@ -47,7 +47,7 @@ shift $((OPTIND - 1)) # Remove the parsed options
# --- Set target directory ---
# Use the first remaining argument as the target directory.
if [ -n "$1" ]; then
if [ "$#" -gt 0 ]; then
TARGET_DIR="$1"
fi
@@ -75,7 +75,7 @@ find "${TARGET_DIR}" -type l ! -exec test -e {} \; -print0 | while IFS= read -r
continue
fi
# Ask the user for confirmation.
read -p "Remove broken symlink '${link}'? [y/N] " -n 1 -r
read -p "Remove broken symlink '${link}'? [y/N] " -n 1 -r < /dev/tty
echo # Move to a new line after input.
if [[ $REPLY =~ ^[Yy]$ ]]; then

View File

@@ -3,7 +3,7 @@
# Installs Ansible, trying user-space methods first before falling back to sudo.
# This script is designed to be idempotent and safe to run multiple times.
set -e # Exit immediately if a command exits with a non-zero status.
set -euo pipefail # Exit immediately if a command exits with a non-zero status, undefined variable, or pipe failure.
# --- Helper Functions ---
info() { echo "[INFO] $1"; }
@@ -44,8 +44,8 @@ fi
# Try Python's venv module if pipx failed or wasn't present
VENV_PATH="${HOME}/.local/share/ansible_venv"
# Create a temp path to avoid clobbering a failed install
VENV_TEST_PATH="/tmp/ansible_venv_test_$$"
# Create a temp path securely to avoid clobbering a failed install
VENV_TEST_PATH="$(mktemp -d "${TMPDIR:-/tmp}/ansible_venv_test.XXXXXX")"
if python3 -m venv "${VENV_TEST_PATH}" >/dev/null 2>&1; then
rm -rf "${VENV_TEST_PATH}" # Clean up test
info "Python's venv module is available. Creating a virtual environment at ${VENV_PATH}..."
@@ -55,7 +55,7 @@ if python3 -m venv "${VENV_TEST_PATH}" >/dev/null 2>&1; then
info "Ansible installed successfully into a virtual environment."
info "To use it, run: '${VENV_PATH}/bin/ansible'"
info "To make it available everywhere, add its bin directory to your PATH:"
info " echo 'export PATH="${VENV_PATH}/bin:$PATH"' >> ~/.profile"
info " echo 'export PATH=\"${VENV_PATH}/bin:\$PATH\"' >> ~/.profile"
info "(You may need to source ~/.profile or restart your shell)."
exit 0
else
@@ -63,6 +63,7 @@ if python3 -m venv "${VENV_TEST_PATH}" >/dev/null 2>&1; then
rm -rf "${VENV_PATH}" # Clean up failed attempt
fi
else
rm -rf "${VENV_TEST_PATH}" # Clean up test after failure
info "Python's venv module not available or failed to create a test environment."
fi

View File

@@ -1,9 +1,11 @@
#!/bin/bash
set -ue
set -ueo pipefail
TMPDIR=$(mktemp -d)
SYS_TMPDIR="${TMPDIR:-/tmp}"
TMPDIR="$(mktemp -d "${SYS_TMPDIR%/}/install_tool.XXXXXX")"
trap 'rm -rf -- "${TMPDIR}"' EXIT
export -n TMPDIR 2>/dev/null || true
REINSTALL=0
PACKAGES=1
@@ -124,7 +126,7 @@ function get_latest_github_release_url {
local repo="$1"
local glob="$2"
curl -s "https://api.github.com/repos/${repo}/releases/latest" | \
jq -r ".assets[] | select(.name|test(\"${glob}\")) | .browser_download_url"
jq -r --arg rx "${glob}" '.assets[] | select(.name | test($rx)) | .browser_download_url'
}
function require {
@@ -466,7 +468,8 @@ EOF
ropper)
deb_only
install_pkgs python3-z3
pip3 install --user pyvex ropper
require pipx
pipx install ropper
;;
kubeconform)
go install github.com/yannh/kubeconform/cmd/kubeconform@latest

View File

@@ -2,12 +2,20 @@
set -ue
if [ "$(id -u)" -ne 0 ]; then
echo "Error: This script must be run as root." >&2
exit 1
fi
cat >/usr/local/bin/x-resize <<"EOF"
#!/bin/sh
PATH=/usr/bin:/bin:/usr/local/bin
desktopuser=$(/bin/ps -ef | /bin/grep -oP '^\w+ (?=.*vdagent( |$))') || exit 0
desktopuser=$(/bin/ps -eo user,comm 2>/dev/null | awk '$2 ~ /vdagent/ {print $1; exit}')
[ -z "$desktopuser" ] && exit 0
desktophome=$(getent passwd "$desktopuser" | cut -d: -f6)
[ -z "$desktophome" ] && exit 0
export DISPLAY=:0
export XAUTHORITY=$(eval echo "~$desktopuser")/.Xauthority
export XAUTHORITY="${desktophome}/.Xauthority"
/usr/bin/xrandr --output $(/usr/bin/xrandr | awk '/ connected/{print $1; exit; }') --auto
EOF
chmod 755 /usr/local/bin/x-resize

View File

@@ -182,13 +182,14 @@ if [[ -f "$TARGET_FILE" && "$OVERWRITE" != "true" ]]; then
fi
# 4. If the path ends in .md (case-insensitive), generate appropriate YAML front matter and write it to the new file.
if [[ "${TARGET_BASE,,}" == *.md ]]; then
if [[ "$TARGET_BASE" =~ \.[mM][dD]$ ]]; then
NOTE_TITLE="${TARGET_BASE%.*}"
NOTE_TITLE_ESCAPED="${NOTE_TITLE//\"/\\\"}"
CURRENT_DATE="$(date +"%Y-%m-%d %H:%M")"
cat << EOF > "$TARGET_FILE"
---
title: "$NOTE_TITLE"
title: "$NOTE_TITLE_ESCAPED"
date: $CURRENT_DATE
tags: []
---

View File

@@ -12,8 +12,8 @@ set -o pipefail
# For this script, we assume the user's home directory.
SOURCE_DIR="${HOME}"
# Exclude file location. We'll create a default one next to the script.
EXCLUDE_FILE="$HOME/.restic_exclude.darwin"
# Exclude file location.
EXCLUDE_FILE="${HOME}/.restic_exclude.darwin"
# --- Functions ---
usage() {
@@ -34,7 +34,7 @@ EOF
# --- Main Script ---
# Check if restic is installed
if ! command -v restic &> /dev/null; then
if ! command -v restic >/dev/null 2>&1; then
echo "Error: restic command not found." >&2
echo "Please install restic first: https://restic.net/" >&2
exit 1
@@ -57,7 +57,7 @@ while getopts ":l:bu:h" opt; do
;;
b)
BACKUP_MODE="b2"
if [[ ${OPTIND} -le $# && "${!OPTIND}" != -* ]]; then
if [[ ${OPTIND} -le $# && "${!OPTIND:-}" != -* ]]; then
REPO="b2:${!OPTIND}:"
OPTIND=$((OPTIND + 1))
fi
@@ -84,70 +84,86 @@ done
# --- Pre-run checks ---
if [[ -z "${BACKUP_MODE}" ]]; then
echo "Error: You must specify a backup mode (-l or -b)." >&2
usage
exit 1
echo "Error: You must specify a backup mode (-l or -b)." >&2
usage
exit 1
fi
if [[ "${BACKUP_MODE}" == "b2" ]]; then
if [[ -f "${HOME}/.resticb2" ]] ; then
. "${HOME}/.resticb2"
fi
export B2_ACCOUNT_ID
export B2_ACCOUNT_KEY
export B2_BUCKET_NAME
if [[ -z "${B2_ACCOUNT_ID:-}" || -z "${B2_ACCOUNT_KEY:-}" ]]; then
echo "Error: For Backblaze B2 backups, you must set the B2_ACCOUNT_ID and B2_ACCOUNT_KEY environment variables." >&2
exit 1
fi
if [[ -f "${HOME}/.resticb2" ]] ; then
# shellcheck disable=SC1090
. "${HOME}/.resticb2"
fi
export B2_ACCOUNT_ID="${B2_ACCOUNT_ID:-}"
export B2_ACCOUNT_KEY="${B2_ACCOUNT_KEY:-}"
export B2_BUCKET_NAME="${B2_BUCKET_NAME:-}"
if [[ -z "${B2_ACCOUNT_ID}" || -z "${B2_ACCOUNT_KEY}" ]]; then
echo "Error: For Backblaze B2 backups, you must set the B2_ACCOUNT_ID and B2_ACCOUNT_KEY environment variables." >&2
exit 1
fi
if [[ -z "${REPO:-}" ]]; then
if [[ -n "${B2_BUCKET_NAME:-}" ]]; then
REPO="b2:${B2_BUCKET_NAME}:"
else
echo "Error: Backup mode is B2 but no bucket name was provided and the B2_BUCKET_NAME environment variable is not set." >&2
usage
exit 1
fi
if [[ -z "${REPO}" ]]; then
if [[ -n "${B2_BUCKET_NAME}" ]]; then
REPO="b2:${B2_BUCKET_NAME}:"
else
echo "Error: Backup mode is B2 but no bucket name was provided and the B2_BUCKET_NAME environment variable is not set." >&2
usage
exit 1
fi
fi
fi
KEYCHAIN_ENTRY_NAME="restic_repo_password"
if security find-generic-password -a "$(whoami)" -s "${KEYCHAIN_ENTRY_NAME}" >/dev/null 2>&1 ; then
export RESTIC_PASSWORD_COMMAND="security find-generic-password -a \"$(whoami)\" -s \"${KEYCHAIN_ENTRY_NAME}\" -w"
local_user="$(id -un 2>/dev/null || whoami)"
if security find-generic-password -a "${local_user}" -s "${KEYCHAIN_ENTRY_NAME}" >/dev/null 2>&1 ; then
printf -v RESTIC_PASSWORD_COMMAND 'security find-generic-password -a %q -s %q -w' "${local_user}" "${KEYCHAIN_ENTRY_NAME}"
export RESTIC_PASSWORD_COMMAND
# Source file?
elif [[ -f "${HOME}/.resticpass" ]] ; then
export RESTIC_PASSWORD_FILE="${HOME}/.resticpass"
fi
# Ensure exclude file exists so restic does not fail when checking exclusions.
if [[ ! -f "${EXCLUDE_FILE}" ]]; then
echo "Exclude file '${EXCLUDE_FILE}' not found. Creating a default macOS exclude file..."
cat << 'EOF' > "${EXCLUDE_FILE}"
# Default restic exclusions for macOS
.Trash
Library/Caches
Library/Logs
.CFUserTextEncoding
EOF
fi
# If the repository does not exist, initialize it.
# The user will be prompted for a password, which will be required for all
# future interactions with the repository.
if ! restic -r "${REPO}" snapshots &> /dev/null; then
echo "Restic repository not found or not accessible. Initializing..."
restic init -r "${REPO}"
if ! restic -r "${REPO}" snapshots >/dev/null 2>&1; then
echo "Restic repository not found or not accessible. Initializing..."
restic init -r "${REPO}"
fi
# --- Run Backup ---
echo "Starting restic backup..."
echo "Source: ${SOURCE_DIR}"
echo "Repository: ${REPO}"
BACKUP_CMD="restic backup \
--verbose \
--repo \"${REPO}\" \
--exclude-file \"${EXCLUDE_FILE}\" \
--one-file-system \
--tag \"macbook-backup\""
BACKUP_ARGS=(
"restic" "backup"
"--verbose"
"--repo" "${REPO}"
"--exclude-file" "${EXCLUDE_FILE}"
"--one-file-system"
"--tag" "macbook-backup"
)
if [[ -n "${UPLOAD_LIMIT}" ]]; then
BACKUP_CMD="${BACKUP_CMD} --limit-upload ${UPLOAD_LIMIT}"
BACKUP_ARGS+=("--limit-upload" "${UPLOAD_LIMIT}")
fi
BACKUP_CMD="${BACKUP_CMD} \"${SOURCE_DIR}\""
BACKUP_ARGS+=("${SOURCE_DIR}")
eval "${BACKUP_CMD}"
"${BACKUP_ARGS[@]}"
echo "Backup complete."
@@ -155,11 +171,11 @@ echo "Backup complete."
# Keeps the last 7 daily, 4 weekly, and 6 monthly snapshots.
echo "Pruning old snapshots..."
restic forget \
--repo "${REPO}" \
--keep-daily 7 \
--keep-weekly 4 \
--keep-monthly 6 \
--prune
--repo "${REPO}" \
--keep-daily 7 \
--keep-weekly 4 \
--keep-monthly 6 \
--prune
echo "Pruning complete."
echo "Restic backup script finished."

View File

@@ -72,15 +72,51 @@ shift # Consume the subcommand
# Separate arguments from the file to be signed
declare -a remaining_args
file_to_sign=""
f_provided=false
n_provided=false
I_provided=false
s_provided=false
while [[ "$#" -gt 0 ]]; do
# If we see a non-flag argument, assume it's the file to sign.
# This works because the file to sign is the only positional argument.
if [[ "$1" != -* ]] && [[ -z "$file_to_sign" ]]; then
file_to_sign="$1"
else
remaining_args+=("$1")
fi
shift
case "$1" in
-f)
[[ -z "${2:-}" ]] && error "Option -f requires an argument."
remaining_args+=("-f" "$2")
f_provided=true
shift 2
;;
-n)
[[ -z "${2:-}" ]] && error "Option -n requires an argument."
remaining_args+=("-n" "$2")
n_provided=true
shift 2
;;
-I)
[[ -z "${2:-}" ]] && error "Option -I requires an argument."
remaining_args+=("-I" "$2")
I_provided=true
shift 2
;;
-s)
[[ -z "${2:-}" ]] && error "Option -s requires an argument."
remaining_args+=("-s" "$2")
s_provided=true
shift 2
;;
-h|--help)
usage
;;
-*)
error "Unknown option: $1"
;;
*)
if [[ -n "$file_to_sign" ]]; then
error "Unexpected positional argument '$1' (already specified '$file_to_sign')."
fi
file_to_sign="$1"
shift
;;
esac
done
# --- Build command based on subcommand ---
@@ -90,18 +126,6 @@ CMD_ARGS=("ssh-keygen" "-Y" "$SUBCOMMAND")
# Append all the flag-based arguments (-f, -n, -I, -s)
CMD_ARGS+=("${remaining_args[@]}")
# Scan for provided flags to handle defaults correctly
f_provided=false
n_provided=false
I_provided=false
s_provided=false
for arg in "${remaining_args[@]}"; do
[[ "$arg" == "-f" ]] && f_provided=true
[[ "$arg" == "-n" ]] && n_provided=true
[[ "$arg" == "-I" ]] && I_provided=true
[[ "$arg" == "-s" ]] && s_provided=true
done
if [[ "$SUBCOMMAND" == "sign" ]]; then
if [[ -z "$file_to_sign" ]]; then
error "Path to file to be signed is required for 'sign' command."

View File

@@ -260,6 +260,7 @@ if [[ -f "${TARGET_FILE}" ]]; then
fi
MANAGED_SIGS_TMP=$(mktemp)
CLEANUP_FILES+=("${MANAGED_SIGS_TMP}")
echo "${MANAGED_BLOCK}" | awk '/^[^#]/ {
n = split($0, parts, " ")
sig = ""

View File

@@ -1,7 +1,49 @@
#!/bin/sh
set -e
SKEL_DIR=$(dirname -- "$(readlink -f -- "$HOME/.profile")")
cd -- "$SKEL_DIR"
cd -- "$(git rev-parse --show-toplevel)"
set -eu
resolve_symlink() {
_target="$1"
if command -v readlink >/dev/null 2>&1 && readlink -f -- "$_target" >/dev/null 2>&1; then
readlink -f -- "$_target"
elif command -v python3 >/dev/null 2>&1; then
python3 -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$_target"
else
while [ -L "$_target" ]; do
_dir=$(cd -P "$(dirname -- "$_target")" >/dev/null 2>&1 && pwd)
_target=$(readlink "$_target")
case "$_target" in
/*) ;;
*) _target="$_dir/$_target" ;;
esac
done
echo "$_target"
fi
}
if [ -e "$HOME/.profile" ]; then
TARGET=$(resolve_symlink "$HOME/.profile")
SKEL_DIR=$(dirname -- "$TARGET")
else
SKEL_DIR=""
fi
REPO_ROOT=""
if [ -n "$SKEL_DIR" ] && cd -- "$SKEL_DIR" 2>/dev/null; then
REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || true)
fi
if [ -z "$REPO_ROOT" ] || [ ! -f "$REPO_ROOT/install.sh" ]; then
SCRIPT_DIR=$(dirname -- "$(resolve_symlink "$0")")
if cd -- "$SCRIPT_DIR" 2>/dev/null; then
REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || true)
fi
if [ -z "$REPO_ROOT" ] || [ ! -f "$REPO_ROOT/install.sh" ]; then
echo "Error: Could not determine skel repository root." >&2
exit 1
fi
fi
cd -- "$REPO_ROOT"
git pull
./install.sh
./install.sh "$@"