#!/usr/bin/env bash
# SwiftPods: verify the pinned installer of a release, then create a verified private runtime.
# Usage: install.sh --version X.Y.Z --installer-sha256 HEX --manifest-sha256 HEX
# swiftpods.org/downloads fills in these values from the latest GitHub release.
set -euo pipefail

swiftpods_setup_directory=''
swiftpods_runtime_parent=''
swiftpods_keep_runtime=false

cleanup() {
  if [[ -n "$swiftpods_setup_directory" ]]; then
    rm -r -- "$swiftpods_setup_directory"
  fi
  if [[ -n "$swiftpods_runtime_parent" && "$swiftpods_keep_runtime" != true ]]; then
    rm -r -- "$swiftpods_runtime_parent"
  fi
}
trap cleanup EXIT

usage() {
  printf '%s\n' "$1" \
    'Usage: install.sh --version X.Y.Z --installer-sha256 HEX --manifest-sha256 HEX' \
    'Copy the complete command from https://swiftpods.org/downloads/#ci.' >&2
  exit 2
}

main() {
  local version='' installer_sha256='' manifest_sha256=''
  while (($#)); do
    (($# >= 2)) || usage "Missing value for $1."
    case "$1" in
      --version) version="$2" ;;
      --installer-sha256) installer_sha256="$2" ;;
      --manifest-sha256) manifest_sha256="$2" ;;
      *) usage "Unknown argument: $1" ;;
    esac
    shift 2
  done
  [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || usage 'Pass the release version, such as --version 1.2.3.'
  [[ "$installer_sha256" =~ ^[0-9a-f]{64}$ ]] || usage 'Pass the complete SHA-256 of install.py with --installer-sha256.'
  [[ "$manifest_sha256" =~ ^[0-9a-f]{64}$ ]] || usage 'Pass the complete SHA-256 of release.json with --manifest-sha256.'

  local temporary="${TMPDIR:-/tmp}"
  temporary="${temporary%/}"
  swiftpods_setup_directory="$(mktemp -d "$temporary/swiftpods-setup.XXXXXX")"

  local prefix="${SWIFTPODS_INSTALL_PREFIX:-$PWD/.build/swiftpods/$version-${manifest_sha256:0:12}}"
  local installer="$swiftpods_setup_directory/install.py"
  local runtime="${SWIFTPODS_RUNTIME_DIRECTORY:-}"

  curl --fail --silent --show-error --location \
    --connect-timeout 15 --max-time 120 --retry 2 \
    "https://github.com/swiftpods-org/swiftpods/releases/download/v$version/install.py" \
    --output "$installer"
  printf '%s  %s\n' "$installer_sha256" "$installer" | shasum -a 256 -c -

  if [[ -z "$runtime" ]]; then
    swiftpods_runtime_parent="$(mktemp -d "$temporary/swiftpods-runtime.XXXXXX")"
    chmod 700 "$swiftpods_runtime_parent"
    runtime="$swiftpods_runtime_parent/runtime"
    mkdir -m 700 "$runtime"
  fi
  python3 "$installer" --version "$version" \
    --manifest-sha256 "$manifest_sha256" --prefix "$prefix" \
    --runtime-directory "$runtime"
  swiftpods_keep_runtime=true

  printf '\nSwiftPods %s is installed.\nVerified executable: %s/swiftpods\n' "$version" "$runtime"
  printf 'For this terminal or CI job:\nexport PATH=%q:$PATH\n' "$runtime"
  printf 'Keep the private runtime directory while using SwiftPods; recreate it for the next CI job.\n'
}

main "$@"
