Files
pixi-deploy/autodeploy/download.sh
T
2025-04-16 10:42:07 +02:00

143 lines
2.9 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 download() {
local url=$1
local archive=$2
local binary=$3
if check_meta "$url" "$archive"; then
echo "Skipping download $url"
return
fi
echo "Downloading $url ..."
rm "$archive" "$binary" || true
curl --location --silent --show-error --remote-time --output "$archive" "$url"
tar xzf "$archive"
}
function check_meta() {
local url=$1
local fn=$2
local local_meta remote_meta
if [ ! -f "$fn" ]; then
echo "File $fn not found"
return 1
fi
local_meta=$(get_local_meta "$fn")
remote_meta=$(get_remote_meta "$url")
if [ "$remote_meta" != "$local_meta" ]; then
echo "Remote and local meta data of file $fn differ (remote: $remote_meta, local: $local_meta)"
return 1
else
echo "Remote and local meta data of file $fn are identical ($remote_meta)"
return 0
fi
}
function get_local_meta() {
local fn=$1
stat --format "s:%s|t:%Y" "$fn"
}
function get_remote_meta() {
local url=$1
header=$(get_header "$url")
size=$(extract_from "$header" "content-length")
time=$(extract_from "$header" "last-modified")
time=$(date --date "$time" +%s)
echo "s:$size|t:$time"
}
function get_header() {
local url=$1
curl --head --location --silent --show-error "$url"
}
function extract_from() {
local header=$1
local entry=$2
echo "$header" | grep "^${entry}:" | tail -n 1 | cut -d ' ' -f 2- | tr -d "\r"
}
download "$URL" "$ARCHIVE" "$BINARY"