#!/bin/sh
# Stable HydraTerms Linux bootstrap. The signed web release binds these exact bytes and the
# versioned installer below; the child retains the narrowly scoped privileged operations.
set -eu

main() {
  installer_url='https://hydraterms.com/assets/install-hydraterms-linux-0.2.15-66efd9747ad0.sh'
  installer_sha256='66efd9747ad0d14073de0b4dc0e41820dd72c94a81e2dbf35f3f0393339d42b7'

  fail() {
    printf 'Hydra installation failed: %s\n' "$1" >&2
    exit 1
  }

  for command_name in curl mktemp sha256sum; do
    command -v "$command_name" >/dev/null 2>&1 || fail "required command is missing: $command_name"
  done

  umask 077
  installer="$(mktemp "${TMPDIR:-/tmp}/hydraterms-bootstrap.XXXXXX")" || \
    fail 'could not create a temporary installer file'
  cleanup() {
    rm -f -- "$installer"
  }
  trap cleanup 0
  trap 'exit 129' HUP
  trap 'exit 130' INT
  trap 'exit 143' TERM

  curl --fail --silent --show-error --proto '=https' --proto-redir '=https' --tlsv1.2 \
    --max-redirs 0 --max-filesize 1048576 --connect-timeout 15 --max-time 120 \
    --output "$installer" "$installer_url" || fail 'versioned installer download failed'
  printf '%s  %s\n' "$installer_sha256" "$installer" | \
    sha256sum --check --strict >/dev/null || fail 'versioned installer integrity check failed'

  child_stdin='/dev/null'
  if ( : </dev/tty ) 2>/dev/null; then
    child_stdin='/dev/tty'
  fi
  sh "$installer" "$@" <"$child_stdin" || fail 'versioned installer failed'
}

# Keep every side effect behind this final call: a truncated bootstrap cannot start installation.
main "$@"
