Files
pixi-deploy/autodeploy/download.sh
T

133 lines
2.8 KiB
Bash
Executable File

#!/bin/bash
set -euo pipefail
function print_help() {
cat << EOF
Usage: $(basename "$0") [OPTIONS] URL
Downloads ARCHIVE from URL and extracts BINARY from it,
but only if the remote file differs from the local file.
Positional arguments:
URL The url to download ARCHIVE from
Optional arguments:
-a, --archive ARCHIVE The name of the downloaded archive (default: inferred from URL)
-b, --binary BINARY The binary to extract from ARCHIVE (default: inferred from ARCHIVE)
-h, --help Show this help message and exit
EOF
}
ARCHIVE=""
BINARY=""
POSITIONAL_ARGS=()
while [[ $# -gt 0 ]]; do
case "$1" in
-a|--archive)
ARCHIVE="$2"
shift 2
;;
-b|--binary)
BINARY="$2"
shift 2
;;
-h|--help)
print_help
exit 0
;;
-*)
echo "Unknown option: $1"
print_help
exit 1
;;
*)
POSITIONAL_ARGS+=("$1")
shift
;;
esac
done
if [[ ${#POSITIONAL_ARGS[@]} -ne 1 ]]; then
echo "Error: Missing required positional argument: URL"
echo
print_help
exit 1
fi
URL="${POSITIONAL_ARGS[0]}"
[[ -z "$ARCHIVE" ]] && ARCHIVE=$(basename "$URL")
[[ -z "$BINARY" ]] && BINARY=$(echo "$ARCHIVE" | cut -d. -f1 | cut -d- -f1)
#echo "url: $URL"
#echo "archive: $ARCHIVE"
#echo "binary: $BINARY"
function ensure_binary() {
local url=$1
local archive=$2
local binary=$3
if [ -f "$binary" ]; then
echo "File $binary exists already"
return
fi
update "$url" "$archive"
tar xzf "$archive"
}
function update() {
local url=$1
local archive=$2
if ! check_file_sizes "$url" "$archive"; then
echo "Downloading $url (if remote is newer) ..."
curl --location --remote-time --time-cond "$archive" --output "$archive" "$url"
else
echo "Skipped download $url"
fi
}
function check_file_sizes() {
local url=$1
local fn=$2
local local_size remote_size
if [ ! -f "$fn" ]; then
echo "File $fn not found"
return 1
fi
local_size=$(get_local_file_size "$fn")
remote_size=$(get_remote_file_size "$url")
if [ "$remote_size" -ne "$local_size" ]; then
echo "Remote and local size of file $fn differs (remote: $remote_size, local: $local_size)"
return 1
fi
echo "Remote and local size of file $fn is identical"
return 0
}
function get_local_file_size() {
local fn=$1
stat --format="%s" "$fn"
}
function get_remote_file_size() {
local url=$1
curl --location --head --silent "$url" | grep -i "content-length" | tail -n 1 | cut -d ' ' -f 2 | tr -d '\r'
}
ensure_binary "$URL" "$ARCHIVE" "$BINARY"