#!/bin/sh set -eu export LC_ALL=C umask 077 fail() { printf 'orz installer: %s\n' "$*" >&2 exit 1 } download() ( url=$1 file=$2 limit=$3 set -- --proto "=$protocol" if [ "$protocol" = http ]; then set -- "$@" --noproxy '*' fi status=$(curl -q --globoff "$@" --fail --silent --show-error \ --max-time 120 --max-filesize "$limit" --output "$file" --write-out '%{http_code}' "$url") || fail "download failed for $url" [ "$status" = 200 ] || fail "unexpected HTTP $status for $url" [ "$(wc -c < "$file")" -le "$limit" ] || fail 'download exceeds size limit' ) configure_profile() ( profile=$1 parent=${profile%/*} # Resolve the parent before opening the profile, and skip redirected paths. expected_parent=$(realpath -ms -- "$parent") || return 1 cd -P -- "$parent" >/dev/null && [ "$PWD" = "$expected_parent" ] || return 1 exec 9< . || return 1 flock -x -w 5 9 || return 1 file=./${profile##*/} [ ! -L "$file" ] && [ -f "$file" ] && [ -O "$file" ] && [ -r "$file" ] && [ -w "$file" ] && [ "$(stat -c %h -- "$file")" = 1 ] || return 1 marker="$profile_line # orz installer PATH" if grep -Fxqe "$marker" -e "$path_command" -- "$file"; then printf 'PATH setup already present in %s\n' "$profile" elif [ "$?" -eq 1 ] && [ ! -L "$file" ] && [ -f "$file" ] && printf '\n%s\n' "$marker" >> "$file"; then printf 'Added orz to PATH in %s\n' "$profile" else return 1 fi ) setup_profile() { if configure_profile "$1" 2>/dev/null; then if [ "$activate_now" = yes ]; then printf 'Open a new shell, or reload this profile with %s\n' "$2" fi else printf 'Add this line to %s and open a new shell\n %s\n' "$1" "$path_command" fi } configure_path() { path_command='export PATH="$HOME/.local/share/orz/bin:$PATH"' profile_line='case "${PATH-}:" in "$HOME/.local/share/orz/bin:"*) ;; *) export PATH="$HOME/.local/share/orz/bin${PATH:+:$PATH}" ;; esac' shell_name=${SHELL:-} shell_name=${shell_name##*/} case "$shell_name" in fish) path_command='fish_add_path --path --move "$HOME/.local/share/orz/bin"' profile_line=$path_command ;; csh|tcsh) path_command='setenv PATH "$HOME/.local/share/orz/bin:$PATH"' ;; nu) path_command='$env.PATH = ($env.PATH | prepend ($env.HOME | path join .local share orz bin))' ;; esac if [ "$destination" != "$HOME/.local/share/orz/bin" ]; then quoted=$(printf '%s' "$destination" | sed "s/'/'\\\\''/g") path_command="export PATH='$quoted':\"\$PATH\"" profile_line="case \"\${PATH-}:\" in '$quoted:'*) ;; *) export PATH='$quoted'\"\${PATH:+:\$PATH}\" ;; esac" case "$shell_name" in fish) quoted=$(printf '%s' "$destination" | sed "s/\\\\/\\\\\\\\/g; s/'/\\\\'/g") path_command="fish_add_path --path --move '$quoted'" profile_line=$path_command ;; csh|tcsh) path_command="setenv PATH '$quoted':\"\$PATH\"" ;; nu) quoted=$(jq -nr --arg dir "$destination" '$dir | @json') path_command="\$env.PATH = (\$env.PATH | prepend $quoted)" ;; esac fi activate_now=yes case "${PATH-}:" in "$destination:"*) activate_now=no ;; esac if [ "$modify_path" = yes ]; then case "$shell_name" in bash) setup_profile "$HOME/.bashrc" '. "$HOME/.bashrc"' for login_profile in .bash_profile .bash_login .profile; do if [ -e "$HOME/$login_profile" ]; then setup_profile "$HOME/$login_profile" ". \"\$HOME/$login_profile\"" break fi done ;; zsh) setup_profile "${ZDOTDIR:-$HOME}/.zshrc" '. "${ZDOTDIR:-$HOME}/.zshrc"' ;; fish) config_home=${XDG_CONFIG_HOME:-} case "$config_home" in /*) ;; *) config_home=$HOME/.config ;; esac setup_profile "$config_home/fish/config.fish" 'source "$__fish_config_dir/config.fish"' ;; *) printf 'Add %s as the first PATH entry in your shell startup file.\n' "$destination" ;; esac fi if [ "$activate_now" = yes ]; then printf 'To use orz in this session, run the following in your shell\n %s\n' "$path_command" fi } json() ( program=$1 shift jq -ers --arg project_path "$product_path" --arg api_path "$api_path" \ --arg base "$base" --arg origin "$origin" --arg channel "$channel" \ --arg version "$version" --arg channel_path "$channel_path" \ --argjson key "$channel_id" --argjson boundary "$boundary" \ --arg suffix "$suffix" \ "$(cat "$work/validation.jq") select(length == 1) | .[0] | ($program)" "$@" ) resolve_rolling() { cursor= job= pages=0 while [ "$pages" -lt 64 ]; do pages=$((pages + 1)) url=$base$channel_path [ -z "$cursor" ] || url=$url?cursor=$cursor download "$url" "$work/listing" 1048576 record=$(json ' select(.product == "orz" and (.url | matches($channel_path)) and (.channel | .key == $key and .name == $channel and .kind == "rolling" and .visibility == "public") and .mutable == true and .temporary == true and .retention_hold == false and (.job.number | id) and (.job.name | type == "string" and length > 0) and (.runs | type == "array")) | {job: (.job | {number,name}), run: .runs[0], next_cursor} | @json ' "$work/listing") || fail 'invalid rolling orz channel identity' current_job=$(printf '%s' "$record" | jq -c '.job') [ -z "$job" ] || [ "$job" = "$current_job" ] || fail 'rolling channel Job changed' job=$current_job if printf '%s' "$record" | jq -e '.run != null' >/dev/null; then printf '%s' "$record" | jq -e '.run' > "$work/run" || fail 'invalid rolling orz Run record' suffix=$(json ' select((.run | id) and ($boundary == 0 or .run < $boundary)) | $channel_path + "/runs/" + (.run | tostring) ' "$work/run") || fail 'invalid rolling orz Run number' source_sha=$(json ' select((.job | {number,name}) == $job and .source.ref == $job.name and (.source.sha | sha) and .manually_frozen == false and (.finished_at | type == "string" and test("\\A[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}([.][0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})\\z")) and (.url | matches($suffix))) | .source.sha ' --argjson job "$job" "$work/run") || fail 'invalid rolling orz Run identity' version=0.0.0-dev.$(printf '%.12s' "$source_sha") return fi cursor=$(printf '%s' "$record" | jq -er '.next_cursor | strings | select(test("\\A[A-Za-z0-9_-]{1,32}\\z"))') || fail "rolling channel '$channel' has no available Runs or has an invalid cursor" decoded=$(printf '%s' "$cursor" | jq -Rer ' gsub("-"; "+") | gsub("_"; "/") | . + (["", "", "==", "="][length % 4]) | @base64d | select(test("\\A[1-9][0-9]*:[1-9][0-9]{0,9}\\z")) ') || fail 'invalid rolling channel cursor' next=${decoded#*:} [ "${decoded%%:*}" = "$channel_id" ] && [ "$next" -le 4294967295 ] && { [ "$boundary" -eq 0 ] || [ "$next" -lt "$boundary" ]; } || fail 'invalid rolling channel cursor' boundary=$next done fail 'rolling channel pagination limit reached' } verify_file() { size=$1 digest=$2 filename=$3 output=$4 download "$base$suffix/artifacts/$filename" "$output" "$size" [ "$(wc -c < "$output")" -eq "$size" ] || fail "$filename size mismatch" hash=$(sha256sum "$output") || fail "cannot calculate SHA-256 for $filename" [ "${hash%% *}" = "$digest" ] || fail "$filename checksum mismatch" } restore_install() { for name in .orz-update-channel .orz-release-base orz; do if [ -f "$install_pending/$name" ]; then if [ "$install_pending/$name" -ef "$destination/$name" ]; then continue fi rm -f -- "$work/restore" && ln -- "$install_pending/$name" "$work/restore" && mv -fT -- "$work/restore" "$destination/$name" || return 1 else rm -f -- "$destination/$name" || return 1 fi done mv -fT -- "$install_pending" "$work/recovered" } cleanup() { if [ "${install_started:-no}" = yes ] && [ -d "$install_pending" ]; then restore_install || printf 'orz installer: could not restore previous installation; retry the installer\n' >&2 fi rm -rf -- "$work" } commit_install() { installed=$destination/orz state=$destination/.orz-update-channel release_base=$destination/.orz-release-base install_pending=$destination/.orz-install-pending exec 8>> "$destination/.orz-update.lock" flock -x 8 || fail 'cannot lock installation' # Finish recovery of an earlier updater switch before restoring a bootstrap. if [ -e "$state.pending" ]; then if [ -e "$state.previous-orz" ]; then mv -fT -- "$state.previous-orz" "$installed" || fail 'cannot restore previous executable' fi rm -f -- "$state.pending" || fail 'cannot clear pending channel state' fi rm -f -- "$state.previous-orz" || fail 'cannot clear previous executable backup' if [ -e "$install_pending" ] || [ -L "$install_pending" ]; then [ ! -L "$install_pending" ] && [ -d "$install_pending" ] || fail 'pending installation must be a directory' restore_install || fail 'cannot restore interrupted bootstrap' rm -rf -- "$work/recovered" fi mkdir -- "$work/backup" for name in .orz-update-channel .orz-release-base orz; do target=$destination/$name [ ! -L "$target" ] && { [ ! -e "$target" ] || [ -f "$target" ]; } || fail "existing $name must be a regular file" if [ -e "$target" ]; then ln -- "$target" "$work/backup/$name" || fail "cannot back up $name" fi done previous_base=$default_base if [ -f "$release_base" ]; then previous_base=$(cat "$release_base") fi keep_channel=no if [ -n "${ORZ_VERSION:-}" ] && [ "$previous_base" = "$base" ]; then keep_channel=yes fi printf '%s\n' "$channel_id" > "$work/state" printf '%s\n' "$base" > "$work/base" install_started=yes mv -T -- "$work/backup" "$install_pending" || fail 'cannot stage installation backup' if [ "$keep_channel" = no ]; then if [ "$channel_id" = 0 ]; then rm -f -- "$state" || fail 'cannot clear update channel' else mv -fT -- "$work/state" "$state" || fail 'cannot save update channel' fi fi if [ "$base" = "$default_base" ]; then rm -f -- "$release_base" || fail 'cannot clear release API base' else mv -fT -- "$work/base" "$release_base" || fail 'cannot save release API base' fi mv -fT -- "$work/orz" "$installed" || fail 'cannot replace executable' mv -T -- "$install_pending" "$work/committed" || fail 'cannot commit installation' install_started=no exec 8>&- } main() { modify_path=yes for arg do case "$arg" in --no-modify-path) modify_path=no ;; *) fail "unknown option: $arg" ;; esac done case "$(uname -s)/$(uname -m)" in Linux/x86_64|Linux/amd64) arch=amd64 ;; Linux/aarch64|Linux/arm64) arch=arm64 ;; *) fail "unsupported platform $(uname -s)/$(uname -m); use Linux amd64 or arm64" ;; esac case "${HOME:-}" in /*) ;; *) fail 'HOME must be an absolute path' ;; esac destination=${ORZ_INSTALL_DIR:-$HOME/.local/share/orz/bin} case "$destination" in /*) ;; *) fail 'ORZ_INSTALL_DIR must be an absolute path' ;; esac case "$destination" in *' '*) fail 'ORZ_INSTALL_DIR cannot contain a newline' ;; esac # The installer leaves tool defaults intact. The CLI reads this same override. case "${ORZ_CONFIG:-$HOME/.config/orz/config.toml}" in /*) ;; *) fail 'ORZ_CONFIG must be an absolute path' ;; esac channel=${ORZ_CHANNEL:-} version=${ORZ_VERSION:-} [ -z "$channel" ] || [ -z "$version" ] || fail 'ORZ_CHANNEL and ORZ_VERSION are mutually exclusive' command -v jq >/dev/null 2>&1 || fail 'jq is required' product_path=/api/v0/projects/superarch/releases/products/orz default_base=https://repopack.com$product_path base=${ORZ_RELEASES_URL:-$default_base} while [ "${base%/}" != "$base" ]; do base=${base%/}; done case "$base" in *[[:space:]]*) fail 'ORZ_RELEASES_URL cannot contain whitespace' ;; esac printf '%s' "$base" | grep -Exq 'https?://(\[[[:xdigit:]:.]+\]|[a-zA-Z0-9.-]+)(:[0-9]+)?(/[a-zA-Z0-9._~/-]*)?' || fail 'ORZ_RELEASES_URL must be an HTTP(S) product API base without credentials, query or fragment' authority=${base#*://} authority=${authority%%/*} protocol=${base%%:*} origin=$protocol://$authority api_path=${base#"$origin"} if [ "$protocol" = http ]; then [ "${ORZ_ALLOW_HTTP:-0}" = 1 ] && printf '%s' "$authority" | grep -Exq '(localhost|127(\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|\[::1\])(:[0-9]+)?' || fail 'release URLs must use HTTPS (HTTP requires loopback and ORZ_ALLOW_HTTP=1)' fi mkdir -p -- "$destination" || fail "cannot create $destination" work=$(mktemp -d "$destination/.orz-install.XXXXXX") || fail 'cannot stage installation' trap cleanup EXIT trap 'exit 1' HUP INT TERM cat > "$work/validation.jq" <<'JQ' def matches($path): . == ($base + $path) or . == ($api_path + $path) or . == ($project_path + $path) or . == ($origin + $project_path + $path); def id: type == "number" and floor == . and . > 0 and . <= 4294967295; def sha: type == "string" and test("\\A[0-9a-f]{40}\\z"); def release_version: type == "string" and test("\\A(0|[1-9][0-9]*)[.](0|[1-9][0-9]*)[.](0|[1-9][0-9]*)\\z"); def archives: ["orz-\($version)-linux-amd64.tar.gz", "orz-\($version)-linux-arm64.tar.gz"]; def artifacts: select(type == "array" and (map(.name) | sort) == ((archives + ["SHA256SUMS"]) | sort)) | map(.name as $name | select( (.sha256 | type == "string" and test("\\A[0-9a-f]{64}\\z")) and (.size | id and . <= (if $name == "SHA256SUMS" then 8192 else 67108864 end)) and (.url | matches($suffix + "/artifacts/" + $name))) | {name, size, sha256}) | select(length == 3) | sort_by(.name); JQ channel_id=0 channel_path= boundary=0 suffix= source_sha= kind=release requested_channel=$channel if [ -z "$version" ]; then download "$base/channels?version=3" "$work/discovery" 1048576 json ' select(.schema == "repopack.release.channels" and .version == 3 and .key == "superarch" and .product == "orz") | .channels as $all | select(($all | type == "array") and ($all | all((.key | id) and (.name | type == "string" and test("\\A[a-z][a-z0-9-]*\\z")) and (.kind == "rolling" or .kind == "release") and (.key as $id | .url | matches("/channels/" + ($id | tostring))))) and ($all | length) == ($all | unique_by(.key) | length) and ($all | length) == ($all | unique_by(.name) | length) and (.default_channel == null or (.default_channel as $default | $all | any(.key == $default)))) ' "$work/discovery" > "$work/channels" || fail 'invalid orz channel discovery' available=$(jq -r '[.channels[].name] | join(", ")' "$work/channels") selected=$(json ' .default_channel as $default | .channels[] | select(if $channel == "" then .key == $default else .name == $channel end) | [.key, .name, .kind] | @tsv ' "$work/channels") || { if [ -z "$channel" ]; then fail "no public default channel; set ORZ_CHANNEL on the sh side (available: ${available:-none})" fi fail "unknown channel '$channel' (available: ${available:-none})" } read -r channel_id channel kind < "$work/artifacts" || fail 'invalid rolling Run artifacts' jq -r '.[] | select(.name != "SHA256SUMS") | "\(.sha256) \(.name)"' "$work/artifacts" > "$work/expected-sums" sums=$(jq -r '.[] | select(.name == "SHA256SUMS") | [.size, .sha256, .name] | @tsv' "$work/artifacts") read -r size digest filename < "$work/release" || fail 'missing orz release metadata' else printf 'null\n' | json '$version | select(release_version)' >/dev/null || fail 'ORZ_VERSION must be MAJOR.MINOR.PATCH' fi suffix=/versions/$version if [ -z "$channel_path" ]; then download "$base$suffix" "$work/release" 1048576 fi source_sha=$(json ' select(.product == "orz" and .version == $version and .access == "public" and (.lifecycle == "normal" or .lifecycle == "deprecated") and ($channel == "" or .channel == $channel) and (.url | matches($suffix)) and (.source_sha | sha) and .tag.ref == ("refs/tags/releases/orz/" + $version) and .tag.object_sha == .source_sha) | .source_sha ' "$work/release") || fail 'invalid public orz release identity' json '.artifacts | artifacts' "$work/release" > "$work/artifacts" || fail 'invalid release artifacts' fi name=orz-$version-linux-$arch.tar.gz record=$(jq -er --arg name "$name" '.[] | select(.name == $name) | [.size, .sha256] | @tsv' "$work/artifacts") || fail 'missing platform archive' read -r size digest < "$work/$run_file.normalized" || fail 'invalid rolling Run record' done cmp -s "$work/run.normalized" "$work/exact-run.normalized" || fail 'rolling Run identity or artifacts changed' fi entries=$(tar -tzf "$archive") || fail 'cannot list release archive' [ "$entries" = "$(printf 'BUILD-INFO\norz')" ] || fail 'archive contains unexpected entries' tar -tvzf "$archive" > "$work/entries" || fail 'cannot inspect archive member types' awk 'substr($0, 1, 1) != "-" { exit 1 } END { if (NR != 2) exit 1 }' "$work/entries" || fail 'archive members must be regular files' tar -xOzf "$archive" BUILD-INFO > "$work/build-info" || fail 'cannot extract build metadata' printf 'orz-build-v1\n%s\n%s\nlinux\n%s\n' "$version" "$source_sha" "$arch" > "$work/expected" cmp -s "$work/expected" "$work/build-info" || fail 'archive build metadata mismatch' tar -xOzf "$archive" orz > "$work/orz" || fail 'cannot extract executable' [ -s "$work/orz" ] || fail 'archive executable is empty' # ELF magic, 64-bit little-endian class, and the target machine. header=$(od -An -tx1 -N6 "$work/orz" | tr -d ' \n') machine=$(od -An -tx1 -j18 -N2 "$work/orz" | tr -d ' \n') case "$arch/$header/$machine" in amd64/7f454c460201/3e00|arm64/7f454c460201/b700) ;; *) fail 'archive executable does not match the platform' ;; esac chmod 0755 "$work/orz" [ "$(timeout 5 "$work/orz" --version)" = "orz $version" ] || fail 'archive executable version check failed' [ -n "$requested_channel" ] || channel_id=0 commit_install printf 'Installed orz %s at %s\n' "$version" "$destination/orz" configure_path } main "$@"