#!/usr/bin/env bash set -euo pipefail readonly CLIENT_ID=989305c2-d454-45af-8633-acd7d6cdb075 readonly TENANT_ID=e940439b-df08-4fc7-98df-204a77e4a746 readonly STORAGE_SCOPE=https://storage.azure.com/user_impersonation readonly STORAGE_API_VERSION=2021-08-06 readonly READER_GROUP=grp-tengella-cli-releases-prod-read PLATFORM= platform_label= hash_command=(sha256sum) readonly VERSION_PATTERN='^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' readonly DOWNLOAD_TIMEOUT=(--connect-timeout 30 --speed-limit 1 --speed-time 60) readonly SIGN_IN_TIMEOUT=(--connect-timeout 30 --max-time 60) readonly LABEL_WIDTH=15 login_url=${TENGELLA_INSTALL_LOGIN_URL:-https://login.microsoftonline.com} releases_url=${TENGELLA_INSTALL_RELEASES_URL:-https://ccstdata.blob.core.windows.net/tengella-cli-releases} token= metadata= staging= interactive=false animate=false err_color=false out_color=false tty_color=false cursor_hidden=false live_pid= current_step= init_presentation() { local plain=false if [ "${TERM:-}" = dumb ] || [ -n "${CI:-}" ] || [ -n "${TF_BUILD:-}" ]; then plain=true; fi if [ "$plain" = false ] && [ -t 2 ]; then animate=true [ -n "${NO_COLOR:-}" ] || err_color=true fi if [ "$plain" = false ] && [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then out_color=true; fi if { [ -t 1 ] || [ -t 2 ]; } && { exec 3<>/dev/tty; } 2>/dev/null; then interactive=true if [ "${TERM:-}" != dumb ] && [ -z "${NO_COLOR:-}" ]; then tty_color=true; fi fi } paint() { if [ "$1" = true ]; then printf '\e[%sm%s\e[0m' "$2" "$3" else printf '%s' "$3" fi } heading() { local title=$1 meta=${2:-} printf '%s %s%s\n' "$(paint "$err_color" 34 '◖')" "$(paint "$err_color" 1 "$title")" \ "${meta:+$(paint "$err_color" 2 " · $meta")}" >&2 } row() { local label=$3 [ -z "${4:-}" ] || printf -v label "%-${LABEL_WIDTH}s" "$3" printf ' %s %s%s\n' "$(paint "$err_color" "$2" "$1")" "$label" \ "${4:+$(paint "$err_color" 2 "$4")}" >&2 } notice() { printf ' %s\n' "$(paint "$err_color" 2 "· $*")" >&2 } warn() { printf ' %s %s\n' "$(paint "$err_color" 33 '!')" "$*" >&2 } terminal_columns() { local size size=$(stty size 2>/dev/null <&2) || size= if [[ $size =~ ^[0-9]+\ ([0-9]+)$ ]] && [ "${BASH_REMATCH[1]}" -gt 0 ]; then printf '%s' "${BASH_REMATCH[1]}" else printf '80' fi } file_size() { if [[ $PLATFORM == osx-* ]]; then stat -f %z "$1" else stat -c %s "$1" fi } mib() { printf '%d.%d' $(($1 / 1048576)) $((($1 % 1048576) * 10 / 1048576)) } live_loop() { local label=$1 detail=$2 file=$3 total=$4 start=$SECONDS frame=0 columns body text local frames=(⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏) columns=$(terminal_columns) while :; do if [ -n "$file" ]; then detail="$(mib "$(file_size "$file" 2>/dev/null || printf '0')") / $(mib "$total") MiB · $((SECONDS - start))s" fi printf -v body "%-${LABEL_WIDTH}s%s" "$label" "$detail" text=${body:0:$((columns > 6 ? columns - 5 : 1))} printf '\r %s %s\e[K' "$(paint "$err_color" 34 "${frames[frame % 10]}")" "$text" >&2 frame=$((frame + 1)) sleep 0.08 done } live_stop() { [ -n "$live_pid" ] || return 0 kill "$live_pid" 2>/dev/null || true wait "$live_pid" 2>/dev/null || true live_pid= printf '\r\e[2K' >&2 } step() { current_step=$1 if [ "$animate" = true ]; then live_loop "$1" "${2:-}" "${3:-}" "${4:-0}" & live_pid=$! fi } step_done() { live_stop row '✓' 32 "$current_step" "${1:-}" current_step= } fail() { live_stop if [ -n "$current_step" ]; then row '×' 31 "$current_step"; fi printf '%s\n' "$(paint "$err_color" 31 "tengella install: $*")" >&2 exit 1 } cancel() { printf '%s\n' "$(paint "$err_color" 31 'tengella install: Installation canceled. Nothing was changed.')" >&2 exit 130 } confirm() { local answer printf ' %s [Y/n] ' "$(paint "$tty_color" 1 "$1")" >&3 IFS= read -r answer <&3 || answer=n case $answer in "" | y | Y | yes | YES | Yes) return 0 ;; *) return 1 ;; esac } readonly CHANNELS=(stable preview) readonly CHANNEL_PURPOSES=("Recommended for everyday use" "Try the latest changes") channel_sgr() { if [ "$1" = preview ]; then printf '35'; else printf '32'; fi } choose_channel() { if [ "${TERM:-}" != dumb ]; then select_channel_keys else select_channel_numbered fi } select_channel_numbered() { local answer index printf 'Choose a release channel\n' >&3 for index in "${!CHANNELS[@]}"; do printf ' %d. %-9s %s\n' $((index + 1)) "${CHANNELS[index]}" "${CHANNEL_PURPOSES[index]}" >&3 done while :; do printf 'Select channel number [1] (q cancels): ' >&3 IFS= read -r answer <&3 || cancel case $answer in "" | 1) selected_channel=stable ;; 2) selected_channel=preview ;; q | Q) cancel ;; *) continue ;; esac return done } draw_channel_rows() { local index=$1 i marker name for i in "${!CHANNELS[@]}" 2; do if [ "$i" -eq "$index" ]; then marker=$(paint "$tty_color" 34 '→') else marker=' ' fi if [ "$i" -eq 2 ]; then name=$(printf '%-9s' Cancel) [ "$i" -eq "$index" ] && name=$(paint "$tty_color" 1 "$name") printf '\e[2K %s %s\n' "$marker" "$name" >&3 continue fi name=$(printf '%-9s' "${CHANNELS[i]}") if [ "$i" -eq "$index" ]; then name=$(paint "$tty_color" "1;$(channel_sgr "${CHANNELS[i]}")" "$name") fi printf '\e[2K %s %s %s\n' "$marker" "$name" "$(paint "$tty_color" 2 "${CHANNEL_PURPOSES[i]}")" >&3 done } select_channel_keys() { local key_timeout=0.05 [ "${BASH_VERSINFO[0]}" -ge 4 ] || key_timeout=1 local index=0 key rest rows=3 hint=' · ↑/↓ move · Enter select · Esc cancel' [ "$(terminal_columns)" -gt 66 ] || hint= printf '%s %s%s\n' "$(paint "$tty_color" 34 '◖')" "$(paint "$tty_color" 1 'Choose a release channel')" \ "$(paint "$tty_color" 2 "$hint")" >&3 printf '\e[?25l' >&3 cursor_hidden=true draw_channel_rows "$index" while :; do IFS= read -rsn1 key <&3 || key=$'\x04' case $key in $'\e') rest= IFS= read -rsn2 -t "$key_timeout" rest <&3 || true case $rest in '[A' | OA) index=$(((index + rows - 1) % rows)) ;; '[B' | OB) index=$(((index + 1) % rows)) ;; '[' | '['? | O?) ;; *) index=2 && break ;; esac ;; k) index=$(((index + rows - 1) % rows)) ;; j) index=$(((index + 1) % rows)) ;; 1) index=0 && break ;; 2) index=1 && break ;; '') break ;; q | Q | $'\x03' | $'\x04') index=2 && break ;; esac printf '\e[%dA' "$rows" >&3 draw_channel_rows "$index" done printf '\e[%dA\r\e[J\e[?25h' $((rows + 1)) >&3 cursor_hidden=false [ "$index" -ne 2 ] || cancel selected_channel=${CHANNELS[index]} } copy_user_code() { if [ -n "${WAYLAND_DISPLAY:-}" ] && command -v wl-copy >/dev/null 2>&1; then printf '%s' "$1" | wl-copy 2>/dev/null elif [ -n "${DISPLAY:-}" ] && command -v xclip >/dev/null 2>&1; then printf '%s' "$1" | xclip -selection clipboard 2>/dev/null else return 1 fi } open_browser() { if { [ -n "${DISPLAY:-}" ] || [ -n "${WAYLAND_DISPLAY:-}" ]; } && command -v xdg-open >/dev/null 2>&1; then xdg-open "$1" >/dev/null 2>&1 & fi } usage() { cat <<'EOF' Usage: install.sh [--channel stable|preview] [--migrate-global-tool] Installs the Tengella CLI for the current user. In a terminal it asks before replacing the Tengella.Cli global .NET tool and lets you choose the channel (stable by default). Without a terminal it installs stable unless --channel is given, and replaces a global tool only with --migrate-global-tool. An existing installation runs tengella update on its recorded channel. EOF } check_prerequisites() { case "$(uname -s)/$(uname -m)" in Linux/x86_64) PLATFORM=linux-x64; platform_label='Linux x64' ;; Darwin/arm64) PLATFORM=osx-arm64; platform_label='macOS arm64'; hash_command=(shasum -a 256) ;; Darwin/x86_64) PLATFORM=osx-x64; platform_label='macOS x64'; hash_command=(shasum -a 256) ;; *) fail "This installer supports Linux x64 and macOS arm64/x64 only. Nothing was changed." ;; esac local missing= command for command in curl jq "${hash_command[0]}"; do command -v "$command" >/dev/null 2>&1 || missing="${missing:+$missing }$command" done if [ -n "$missing" ]; then fail "Missing required commands: $missing. Install them and run the installer again. Nothing was changed." fi [ -n "${HOME:-}" ] || fail "HOME is not set. Nothing was changed." } confirm_global_migration() { global_tool=none local version= tools package tool_version rest if command -v dotnet >/dev/null 2>&1 && tools=$(dotnet tool list -g 2>/dev/null); then while read -r package tool_version rest; do if [ "$(printf '%s' "$package" | tr '[:upper:]' '[:lower:]')" = tengella.cli ]; then global_tool=dotnet version=$tool_version fi done <<<"$tools" elif [ -e "$global_shim" ]; then global_tool=orphaned fi [ "$global_tool" != none ] || return 0 [ "$migrate_global_tool" = true ] && return 0 if [ "$interactive" = false ]; then fail "Tengella.Cli global tool found. Run with --migrate-global-tool to replace it without a terminal. Nothing was changed." fi if [ "$global_tool" = dotnet ]; then warn "Tengella.Cli global tool${version:+ $version} found" confirm 'Replace it with the standalone CLI?' || fail "Migration declined. Nothing was changed." else warn "Leftover Tengella.Cli global tool found in ~/.dotnet/tools that dotnet cannot remove" confirm 'Remove it after installing?' || fail "Removal declined. Nothing was changed." fi } migrate_global_installation() { [ "$global_tool" != none ] || return 0 step Migrate "$root/current/tengella" --version >/dev/null 2>&1 || fail "The standalone CLI could not run. The global tool was retained." if [ "$global_tool" = dotnet ]; then dotnet tool uninstall -g Tengella.Cli >/dev/null || fail "Could not uninstall Tengella.Cli. Both installations remain; run the installer again to migrate." else rm -f "$global_shim" rm -rf "$HOME/.dotnet/tools/.store/tengella.cli" fi step_done 'removed Tengella.Cli global tool' } shadowing_tengella() { local resolved hash -r resolved=$(command -v tengella || true) if [ -n "$resolved" ] && [ "$resolved" != "$link" ]; then printf '%s' "$resolved"; fi } fail_sign_in() { local error description error=$(printf '%s' "$1" | jq -r '.error // "unknown_error"') description=$(printf '%s' "$1" | jq -r '.error_description // empty' | head -n 1) fail "Sign-in failed ($error)${description:+: $description}. Nothing was changed." } sign_in() { local response error device_code interval expires_in deadline uri code copied= response=$(curl --silent --show-error "${SIGN_IN_TIMEOUT[@]}" \ --data-urlencode "client_id=$CLIENT_ID" \ --data-urlencode "scope=$STORAGE_SCOPE" \ "$login_url/$TENANT_ID/oauth2/v2.0/devicecode") || fail "Could not reach Microsoft sign-in. Nothing was changed." error=$(printf '%s' "$response" | jq -r '.error // empty') [ -z "$error" ] || fail_sign_in "$response" device_code=$(printf '%s' "$response" | jq -r '.device_code // empty') interval=$(printf '%s' "$response" | jq -r '.interval // 5') expires_in=$(printf '%s' "$response" | jq -r '.expires_in // 0') uri=$(printf '%s' "$response" | jq -r '.verification_uri // empty') code=$(printf '%s' "$response" | jq -r '.user_code // empty') case $uri in https://microsoft.com/devicelogin | https://login.microsoft.com/device) ;; *) fail "Sign-in did not provide a supported device-code flow. Check your sign-in policy. Nothing was changed." ;; esac if [ -z "$device_code" ] || ! [[ $code =~ ^[A-Z0-9-]+$ ]] || ! [[ $interval =~ ^[0-9]+$ ]] || ! [[ $expires_in =~ ^[1-9][0-9]*$ ]]; then fail "Sign-in did not provide a supported device-code flow. Check your sign-in policy. Nothing was changed." fi printf '\n' >&2 heading 'Sign in' 'device code' copy_user_code "$code" && copied=' · copied' printf ' %-6s %s\n' Open "$uri" >&2 printf ' %-6s %s%s\n\n' Code "$(paint "$err_color" 1 "$code")" "${copied:+$(paint "$err_color" 2 "$copied")}" >&2 open_browser "$uri" step 'Sign in' 'waiting for you to sign in' deadline=$((SECONDS + expires_in)) while :; do sleep "$interval" response=$(printf '%s' "$device_code" | curl --silent --show-error "${SIGN_IN_TIMEOUT[@]}" \ --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:device_code" \ --data-urlencode "client_id=$CLIENT_ID" \ --data-urlencode "device_code@-" \ "$login_url/$TENANT_ID/oauth2/v2.0/token") || fail "Could not reach Microsoft sign-in. Nothing was changed." error=$(printf '%s' "$response" | jq -r '.error // empty') case $error in "") token=$(printf '%s' "$response" | jq -r '.access_token // empty') [ -n "$token" ] || fail "Sign-in returned no access token. Nothing was changed." step_done return ;; authorization_pending) ;; slow_down) interval=$((interval + 5)) ;; authorization_declined) fail "Sign-in was canceled. Nothing was changed." ;; expired_token) fail "Sign-in expired before it was completed. Nothing was changed." ;; *) fail_sign_in "$response" ;; esac [ "$SECONDS" -lt "$deadline" ] || fail "Sign-in expired before it was completed. Nothing was changed." done } download_blob() { local name=$1 output=$2 printf 'Authorization: Bearer %s\nx-ms-version: %s\n' "$token" "$STORAGE_API_VERSION" | curl --silent --show-error "${DOWNLOAD_TIMEOUT[@]}" --header @- --output "$output" --write-out '%{http_code}' \ "$releases_url/$name" } require_blob() { local name=$1 output=$2 not_found=$3 status status=$(download_blob "$name" "$output") || fail "Could not download $name from Tengella CLI releases." case $status in 200) ;; 401) fail "Tengella CLI releases did not accept the sign-in. Nothing was changed." ;; 403) fail "Access to Tengella CLI releases was denied. Ask to be added to $READER_GROUP. Nothing was changed." ;; 404) fail "$not_found" ;; *) fail "Tengella CLI releases returned HTTP $status for $name. Nothing was changed." ;; esac } cleanup() { live_stop if [ "$cursor_hidden" = true ]; then printf '\e[?25h' >&3; fi if [ -n "$metadata" ]; then rm -f "$metadata" fi if [ -n "$staging" ]; then rm -rf "$staging" fi } display_path() { case $1 in "$HOME"/*) printf '~/%s' "${1#"$HOME"/}" ;; *) printf '%s' "$1" ;; esac } print_result() { local version=$1 channel=$2 resolved purpose printf '\n %s %s %s\n' "$(paint "$out_color" 32 '✓')" "$(paint "$out_color" 1 "Installed Tengella CLI $version")" \ "$(paint "$out_color" "$(channel_sgr "$channel")" "· $channel")" case ":$PATH:" in *":$bin_dir:"*) ;; *) printf ' %s Add %s to PATH, then open a new terminal:\n' "$(paint "$out_color" 33 '!')" "$(display_path "$bin_dir")" # shellcheck disable=SC2016 # The line is printed for the user to copy. printf ' export PATH="$HOME/.local/bin:$PATH"\n' return ;; esac resolved=$(shadowing_tengella) if [ -n "$resolved" ]; then printf ' %s Another tengella at %s comes first on PATH and runs instead.\n' "$(paint "$out_color" 33 '!')" "$resolved" return fi printf '\n' "$root/current/tengella" --installed-release "$metadata" /dev/null 2>&1 && [ "$(printf '%s' "$artifact" | jq -r '.gzip.path // empty')" = "$path.gz" ]; then gzip_size=$(printf '%s' "$artifact" | jq -r '.gzip.size // empty') if [[ $gzip_size =~ ^[1-9][0-9]*$ ]] && [[ $(printf '%s' "$artifact" | jq -r '.gzip.sha256 // empty') =~ ^[0-9a-fA-F]{64}$ ]]; then gzip_path=$path.gz fi fi step_done "$version · $channel" mkdir -p "$root/versions" staging=$(mktemp -d "$root/.staging.XXXXXX") local started=$SECONDS if [ -n "$gzip_path" ]; then step Download '' "$staging/tengella.gz" "$gzip_size" require_blob "$gzip_path" "$staging/tengella.gz" \ "Release $version is missing its $PLATFORM build. Nothing was changed." if [ "$(file_size "$staging/tengella.gz")" != "$gzip_size" ] || ! gzip -dc <"$staging/tengella.gz" | head -c $((size + 1)) >"$staging/tengella"; then fail "Checksum mismatch for Tengella CLI $version. Nothing was installed." fi rm -f "$staging/tengella.gz" step_done "$(mib "$gzip_size") MiB · $((SECONDS - started))s" else step Download '' "$staging/tengella" "$size" require_blob "$path" "$staging/tengella" \ "Release $version is missing its $PLATFORM build. Nothing was changed." step_done "$(mib "$size") MiB · $((SECONDS - started))s" fi step Verify if [ "$(file_size "$staging/tengella")" != "$size" ] || [ "$("${hash_command[@]}" "$staging/tengella" | cut -d ' ' -f 1)" != "$sha256" ]; then fail "Checksum mismatch for Tengella CLI $version. Nothing was installed." fi chmod +x "$staging/tengella" [ "$("$staging/tengella" --version)" = "$version" ] || fail "Tengella CLI $version did not report its version. Nothing was installed." step_done sha256 step Activate local previous= if [ -L "$root/current" ]; then previous=$(basename "$(readlink "$root/current")") fi rm -rf "${root:?}/versions/$version" mv "$staging" "$root/versions/$version" staging= ln -sfn "versions/$version" "$root/.current.new" if [[ $PLATFORM == osx-* ]]; then mv -fh "$root/.current.new" "$root/current" else mv -Tf "$root/.current.new" "$root/current" fi jq -n --arg channel "$channel" --arg version "$version" \ '{schemaVersion: 1, channel: $channel, version: $version}' >"$root/.install.json.new" mv -f "$root/.install.json.new" "$state" mkdir -p "$bin_dir" [ -L "$link" ] || ln -s "$root/current/tengella" "$link" local directory for directory in "$root"/versions/*; do case ${directory##*/} in "$version" | "$previous") ;; *) rm -rf "$directory" ;; esac done step_done "$(display_path "$root")" migrate_global_installation print_result "$version" "$channel" } main "$@"