#!/usr/bin/env bash

set -euo pipefail

base_url="https://my.userside.eu"
target="./installer"

log() { printf '==> %s\n' "$*" >&2; }
die() { printf 'error: %s\n' "$*" >&2; exit 1; }

## DETERMINE OS AND ARCH

log "detecting platform"

case "$(uname -s)" in
  Linux)   os="linux" ;;
  FreeBSD) os="freebsd" ;;
  *) die "unsupported OS: $(uname -s)" ;;
esac

case "$(uname -m)" in
  x86_64)  arch="amd64" ;;
  aarch64) arch="arm64" ;;
  *) die "unsupported arch: $(uname -m)" ;;
esac

## PICK DOWNLOADER

if command -v curl >/dev/null 2>&1; then
  download() {
    curl \
      --proto '=https' \
      --tlsv1.2 \
      --fail \
      --silent \
      --show-error \
      --location \
      --retry 3 \
      --retry-connrefused \
      --max-time 60 \
      --output "$2" \
      "$1"
  }
elif command -v wget >/dev/null 2>&1; then
  download() {
    wget \
      --https-only \
      --secure-protocol=TLSv1_2 \
      --timeout=30 \
      --tries=3 \
      --retry-connrefused \
      --waitretry=2 \
      --no-verbose \
      --output-document="$2" \
      "$1"
  }
else
  die "neither curl nor wget found"
fi

##

file="installer_${os}_${arch}.gz"
download_url="${base_url}/${file}"
checksums_url="${base_url}/installer.sha256"

## TMP FILES

tmp_gz="$(mktemp "${target}.XXXXXX")"
tmp_bin="$(mktemp "${target}.XXXXXX")"
tmp_sum="$(mktemp "${target}.XXXXXX")"

trap 'rm -f "$tmp_gz" "$tmp_bin" "$tmp_sum"' EXIT

## DOWNLOAD

log "downloading ${file}"
download "$download_url" "$tmp_gz"

log "downloading checksum"
download "$checksums_url" "$tmp_sum"

## VERIFY SHA256

log "verifying sha256"

expected_sha256="$(awk -v f="$file" '$2 == f { print $1 }' "$tmp_sum")"

if [ -z "$expected_sha256" ]; then
  die "checksum for $file not found in installer.sha256"
fi

if command -v sha256sum >/dev/null 2>&1; then
  actual_sha256="$(sha256sum "$tmp_gz" | awk '{ print $1 }')"
elif command -v sha256 >/dev/null 2>&1; then
  actual_sha256="$(sha256 -q "$tmp_gz")"
elif command -v shasum >/dev/null 2>&1; then
  actual_sha256="$(shasum -a 256 "$tmp_gz" | awk '{ print $1 }')"
else
  die "no SHA-256 utility found: sha256sum, sha256, or shasum required"
fi

if [ "$actual_sha256" != "$expected_sha256" ]; then
  printf 'error: checksum mismatch for %s\n' "$file" >&2
  printf 'expected: %s\n' "$expected_sha256" >&2
  printf 'actual:   %s\n' "$actual_sha256" >&2
  exit 1
fi

## EXTRACT AND INSTALL

log "installing to ${target}"

gzip -t "$tmp_gz"
gzip -dc "$tmp_gz" > "$tmp_bin"
chmod 0755 "$tmp_bin"
mv -f "$tmp_bin" "$target"

log "done: ${target}"
