penguin/utils

my env utils

bash/core/20_io.bash

raw ยท 1716 bytes

rbash_url() {
	local path="$1"
	printf '%s/%s/raw/%s/%s/%s\n' \
		"$RBASH_REMOTE" "$RBASH_REPO" "$RBASH_REF" "$RBASH_PATH" "$path"
}

rbash_download() {
	local url="$1"

	if command -v curl >/dev/null 2>&1; then
		curl -fsSL "$url" || {
			local rc=$?
			echo "rbash: download failed: $url" >&2
			echo "rbash: curl exit code: $rc" >&2
			return "$rc"
		}
	elif command -v wget >/dev/null 2>&1; then
		wget -qO- "$url" || {
			local rc=$?
			echo "rbash: download failed: $url" >&2
			echo "rbash: wget exit code: $rc" >&2
			return "$rc"
		}
	else
		echo "rbash: curl or wget is required" >&2
		return 127
	fi
}

function rbash_download_sig {
	local _URL _LOC _SIG tmp

	_SIG="$1"
	_URL="$2"
	_LOC="$3"

	tmp=$( mktemp )
	rbash_download "$_URL" > "$tmp"
	sha256sum "$tmp" | grep -q "$_SIG"
	if [ $? -eq 0 ]; then
		mv "$tmp" "$_LOC"
	else
		echo "Download $_LOC: Signature mismatch" >&2
		return 1
	fi
}

rbash_cache() {
	local sig="$1"
	local url="$2"
	local key file

	if [ -z "${RBASH_CACHE_DIR:-}" ]; then
		echo "rbash: RBASH_CACHE_DIR is not set" >&2
		return 1
	fi

	mkdir -p "$RBASH_CACHE_DIR" || {
		echo "rbash: failed to create cache dir: $RBASH_CACHE_DIR" >&2
		return 1
	}

	if command -v md5sum >/dev/null 2>&1; then
		key="$(printf '%s' "$url" | md5sum | cut -d' ' -f1)"
	else
		key="$(printf '%s' "$url" | md5 | cut -d' ' -f1)"
	fi

	file="$RBASH_CACHE_DIR/$key"

	if [ ! -f "$file" ]; then
		rbash_download_sig "$sig" "$url" "$file" || {
			local rc=$?
			rm -f "$file"
			echo "rbash: download failed: $url" >&2
			return "$rc"
		}
		chmod 700 "$file"
	fi

	printf '%s\n' "$file"
}

_require_jq() {
	if ! command -v jq >/dev/null 2>&1; then
		echo "This command requires jq." >&2
		return 1
	fi
}