#!/bin/sh

set -eu

BIOS_VERSION="${BIOS_VERSION:-0.1.0-rc.3}"
BIOS_INSTALL_ROOT="${BIOS_INSTALL_ROOT:-${XDG_DATA_HOME:-$HOME/.local/share}/bios}"
BIOS_BIN_DIR="${BIOS_BIN_DIR:-$HOME/.local/bin}"
BIOS_RELEASE_BASE_URL="${BIOS_RELEASE_BASE_URL:-https://github.com/bio-xyz/bios-cli/releases/download/bios-cli-v${BIOS_VERSION}}"

fail() {
  printf 'BIOS installer: %s\n' "$*" >&2
  exit 1
}

for command_name in curl tar mktemp sed cmp; do
  command -v "$command_name" >/dev/null 2>&1 || fail "required command not found: $command_name"
done

case "$BIOS_VERSION" in
  ''|*[!0-9A-Za-z.-]*) fail "invalid BIOS_VERSION: $BIOS_VERSION" ;;
esac

system="$(uname -s)"
machine="$(uname -m)"
case "$system-$machine" in
  Linux-x86_64) target="x86_64-unknown-linux-gnu" ;;
  Linux-aarch64|Linux-arm64) target="aarch64-unknown-linux-gnu" ;;
  Darwin-arm64|Darwin-aarch64) target="aarch64-apple-darwin" ;;
  Darwin-x86_64) fail "Intel macOS is not available yet" ;;
  *) fail "unsupported platform: $system $machine" ;;
esac

archive="bios-${BIOS_VERSION}-${target}.tar.gz"
package_root="bios-${BIOS_VERSION}-${target}"
temporary_directory="$(mktemp -d "${TMPDIR:-/tmp}/bios-install.XXXXXX")"
trap 'rm -rf "$temporary_directory"' EXIT HUP INT TERM

printf 'Downloading BIOS %s for %s...\n' "$BIOS_VERSION" "$target"
curl --proto '=https' --tlsv1.2 -fsSL \
  "$BIOS_RELEASE_BASE_URL/$archive" \
  -o "$temporary_directory/$archive"
curl --proto '=https' --tlsv1.2 -fsSL \
  "$BIOS_RELEASE_BASE_URL/$archive.sha256" \
  -o "$temporary_directory/$archive.sha256"

if command -v sha256sum >/dev/null 2>&1; then
  (cd "$temporary_directory" && sha256sum -c "$archive.sha256") >/dev/null
elif command -v shasum >/dev/null 2>&1; then
  (cd "$temporary_directory" && shasum -a 256 -c "$archive.sha256") >/dev/null
else
  fail "sha256sum or shasum is required to verify the download"
fi

tar -tzf "$temporary_directory/$archive" | while IFS= read -r entry; do
  case "$entry" in
    "$package_root"|"$package_root/"|"$package_root/"*) ;;
    *) fail "archive contains an unexpected path: $entry" ;;
  esac
  case "/$entry/" in
    */../*) fail "archive contains an unsafe path: $entry" ;;
  esac
done

tar -xzf "$temporary_directory/$archive" -C "$temporary_directory"
extracted="$temporary_directory/$package_root"
[ -x "$extracted/bin/bios" ] || fail "downloaded package does not contain an executable bin/bios"

versions_directory="$BIOS_INSTALL_ROOT/versions"
version_directory="$versions_directory/$BIOS_VERSION-$target"
mkdir -p "$versions_directory" "$BIOS_BIN_DIR"

if [ -e "$version_directory" ]; then
  [ -x "$version_directory/bin/bios" ] || fail "existing installation is incomplete: $version_directory"
else
  mv "$extracted" "$version_directory"
fi

current_link="$BIOS_INSTALL_ROOT/current"
if [ -e "$current_link" ] && [ ! -L "$current_link" ]; then
  fail "$current_link already exists and is not managed by this installer"
fi

launcher="$BIOS_BIN_DIR/bios"
expected_target="$current_link/bin/bios"
# macOS reports the invoked symlink path as the executable location. Execute
# the binary inside its bundle so BIOS finds its sibling helpers and assets.
# Escape shell metacharacters in the path before embedding it in the launcher.
quoted_target="$(printf '%s' "$expected_target" | sed 's/[\\"$`]/\\&/g')"
new_launcher="$temporary_directory/bios-launcher"
printf '#!/bin/sh\n# Managed by the BIOS installer.\nexec "%s" "$@"\n' "$quoted_target" > "$new_launcher"

if [ -L "$launcher" ]; then
  existing_target="$(readlink "$launcher")"
  [ "$existing_target" = "$expected_target" ] || fail "$launcher points to another installation: $existing_target"
elif [ -e "$launcher" ]; then
  [ -f "$launcher" ] && cmp -s "$new_launcher" "$launcher" \
    || fail "$launcher already exists and is not managed by this installer"
fi

chmod 755 "$new_launcher"
ln -sfn "$version_directory" "$current_link"
# Rename over the old symlink itself; writing through it would replace bios.
mv -f "$new_launcher" "$launcher"

printf '\nBIOS %s installed successfully.\n' "$BIOS_VERSION"
case "$system" in
  Darwin)
    printf 'The macOS prerelease is not signed or notarized and may be blocked by Gatekeeper.\n'
    printf 'Build from source until signed packages are available; do not bypass Gatekeeper.\n'
    ;;
esac
case ":$PATH:" in
  *":$BIOS_BIN_DIR:"*) printf 'Run: bios\n' ;;
  *)
    printf 'Add BIOS to your PATH, then run bios:\n'
    printf '  export PATH="%s:$PATH"\n' "$BIOS_BIN_DIR"
    ;;
esac
