#!/usr/bin/env bash
set -Eeuo pipefail
umask 077

usage() {
  cat <<'HELP'
Usage: cloud-ide install
       cloud-ide up [both|ios|android] [--editor]
       cloud-ide down

Start one Expo SDK 54 Metro workspace and the selected run.cloud devices.
The default starts both. Edit cloud-counter/App.js locally in the demo,
or choose --editor for the browser editor and its live simulator panel.

To use a public, npm-locked Expo SDK 54 checkout instead of the demo:
  PROJECT_REPO=https://github.com/OWNER/REPO.git cloud-ide up --editor
Set PROJECT_REF to select a branch, tag, or commit. Edit that checkout in the
sandbox via its shell or --editor. Use cloud-ide down or Ctrl-C to stop.
HELP
}

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

target=both
editor=false
action=up
case ${1:-} in
  install|up|down) action=$1; shift ;;
esac
if [[ ${1:-} == both || ${1:-} == ios || ${1:-} == android ]]; then
  [[ $action == up ]] || fail 'Choose a device with cloud-ide up.'
  target=$1
  shift
fi
if [[ ${1:-} == --editor ]]; then
  [[ $action == up ]] || fail 'Choose the editor with cloud-ide up.'
  editor=true
  shift
fi
if [[ ${1:-} == --help || ${1:-} == -h ]]; then usage; exit 0; fi
if (( $# )); then usage >&2; exit 2; fi
platforms=(ios android)
if [[ $target != both ]]; then platforms=("$target"); fi

bin_dir=${XDG_BIN_HOME:-$HOME/.local/bin}
runcloud_home=${RUN_CLOUD_HOME:-$HOME/.run-cloud}
export PATH="$bin_dir:$runcloud_home/bin:$PATH"
public_script=https://run.cloud/examples/react-native-cloud-ide.sh
state_root="${XDG_STATE_HOME:-$HOME/.local/state}/runcloud-cloud-ide"
case $action in
  install) dependencies=(curl tar sha256sum flock) ;;
  up) dependencies=(runcloud curl jq tar sha256sum flock) ;;
  down) dependencies=(runcloud jq flock) ;;
esac
if $editor; then dependencies+=(ssh ssh-keygen); fi
for command in "${dependencies[@]}"; do
  command -v "$command" >/dev/null || fail "Install $command before running the workspace."
done

repo=${PROJECT_REPO:-}
ref=${PROJECT_REF:-}
if [[ $action == up && -n $repo && ! $repo =~ ^https://github\.com/[A-Za-z0-9_-]+/[A-Za-z0-9._-]+$ ]]; then
  fail 'Set PROJECT_REPO to a public HTTPS GitHub repository URL.'
fi
if [[ $action == up && -n $ref && ( -z $repo || ! $ref =~ ^[A-Za-z0-9][A-Za-z0-9/_.-]*$ ) ]]; then
  fail 'Set PROJECT_REF to a branch, tag, or commit from PROJECT_REPO.'
fi

workspace=/tmp/cloud-counter
sandbox_name="expo-$(od -An -N12 -tx1 /dev/urandom | tr -d ' \n')"
sandbox_id=
pending_pid=
scratch=
fixture_archive=

receipt() { jq -er '.id | strings | select(length > 0)' "$scratch/$1.json" 2>/dev/null || true; }
guest() {
  local seconds=$1
  shift
  runcloud sandbox exec --timeout "$seconds" "$sandbox_id" "$@"
}

log_failure() {
  local file=$1
  shift
  if [[ -s $file ]]; then
    tail -n 10 "$file" | sed -E \
      -e 's#(https?|exps?|wss?)://[^[:space:]]+#[URL hidden]#g' \
      -e 's#[a-z0-9-]+-box\.run\.cloud#[hostname hidden]#g' \
      -e 's#rc_live_[[:alnum:]_-]+#[API key hidden]#g' >&2
  fi
  printf '%s\n' "$*" >&2
}

export_workspace() {
  local archive="$export_dir/cloud-edits-${sandbox_name#expo-}.tgz"
  local _
  for _ in 1 2; do
    if guest 25 "tar --exclude=node_modules --exclude=.expo --exclude=.git --exclude='.env*' \
      -czf /tmp/cloud-counter-edits.tgz -C '$workspace' ." >"$scratch/export.log" 2>&1 &&
      runcloud sandbox cp "$sandbox_id" :/tmp/cloud-counter-edits.tgz "$scratch/workspace.tgz" >>"$scratch/export.log" 2>&1 &&
      mv -- "$scratch/workspace.tgz" "$archive"; then
      printf 'Saved the remote workspace to %s\n' "$archive"
      return 0
    fi
  done
  log_failure "$scratch/export.log" "Could not export the workspace. Kept sandbox $sandbox_id for recovery."
  printf 'Open runcloud sandbox shell %s to recover your files. When finished, run runcloud sandbox rm %s.\n' "$sandbox_id" "$sandbox_id" >&2
  return 1
}

open_state() {
  mkdir -p -- "$state_root"
  [[ -O $state_root && ! -L $state_root ]] || fail 'Cloud IDE state must be a directory owned by this user.'
  chmod 700 -- "$state_root"
  exec 9>>"$state_root/workspace.lock"
}

active_workspace() {
  local name
  if [[ -s $state_root/active ]]; then
    name=$(<"$state_root/active")
    if [[ $name =~ ^workspace\.[A-Za-z0-9]+$ && -d $state_root/$name && ! -L $state_root/$name ]]; then
      printf '%s\n' "$state_root/$name"
    fi
  fi
}

use_workspace() {
  scratch=$1
  sandbox_name=$(<"$scratch/name")
  export_dir=$(<"$scratch/export-dir")
  editor_ssh_host="runcloud-$sandbox_name"
}

checkpoint() {
  if [[ -e $scratch/stop ]]; then exit 0; fi
}

release_receipt() {
  local resource=$1 id
  shift
  id=$(receipt "$resource")
  if [[ -z $id ]]; then return 0; fi
  if runcloud "$@" "$id" >"$scratch/release.log" 2>&1 ||
    grep -Eiq 'HTTP 404|status.?404|[[:space:]]404[: ]|already released|session is no longer active' "$scratch/release.log"; then
    rm -f -- "$scratch/$resource.json"
    return 0
  fi
  log_failure "$scratch/release.log" "Could not release $resource $id. Retry cloud-ide down."
  return 1
}

cleanup() {
  local status=${1:-$?} platform keep=false
  trap - EXIT
  trap '' HUP INT TERM
  if [[ -n $pending_pid ]]; then
    printf 'Waiting for the current request so its resource can be released.\n' >&2
    wait "$pending_pid" 2>/dev/null || true
  fi
  stop_editor || status=1
  for platform in ios android; do
    if ! release_receipt "$platform" "$platform" delete; then keep=true; fi
  done
  sandbox_id=$(receipt sandbox)
  if [[ -n $sandbox_id ]]; then
    if [[ -e $scratch/ready && -e $scratch/remote-edit && ! -e $scratch/exported ]]; then
      if export_workspace; then
        touch "$scratch/exported"
      else
        keep=true
        sandbox_id=
      fi
    fi
    if [[ -n $sandbox_id ]] && ! release_receipt sandbox sandbox rm; then keep=true; fi
  fi
  for platform in ios android; do
    if ! release_receipt "asset-$platform" asset delete; then keep=true; fi
  done
  if $keep; then exit 1; fi
  if [[ $(active_workspace) == "$scratch" ]]; then rm -f -- "$state_root/active"; fi
  rm -rf -- "$scratch"
  printf 'Cloud IDE stopped.\n'
  exit "$status"
}

stop_workspace() {
  local active _
  open_state
  if flock -n 9; then
    active=$(active_workspace)
  else
    for _ in {1..20}; do
      active=$(active_workspace)
      if [[ -n $active ]]; then break; fi
      sleep 0.1
    done
    if [[ -n $active && -d $active ]]; then
      touch "$active/stop" 2>/dev/null || true
      printf 'Stop requested. Waiting for the workspace to release its resources.\n'
    fi
    if ! flock -w 60 9; then
      printf 'Workspace is still stopping. Run cloud-ide down again to wait.\n'
      return 0
    fi
  fi
  if [[ -z $active || ! -d $active ]]; then
    printf 'No active Cloud IDE workspace.\n'
    return 0
  fi
  use_workspace "$active"
  cleanup 0
}

# Preserve an in-flight create response when the terminal interrupts wait.
provision() {
  local resource=$1
  shift
  (
    trap '' HUP INT TERM
    exec runcloud "$@" --json
  ) >"$scratch/$resource.json" 2>"$scratch/$resource.error" &
  pending_pid=$!
  local status=0
  wait "$pending_pid" || status=$?
  pending_pid=
  if (( status )); then
    log_failure "$scratch/$resource.error" "runcloud could not create $resource (CLI exit $status)."
    exit "$status"
  fi
  if [[ -z $(receipt "$resource") ]]; then fail "runcloud did not return an ID for $resource."; fi
  checkpoint
}

stage_previews() {
  local platform
  editor_runtime=$(guest 20 'umask 077; mktemp -d /tmp/runcloud-previews.XXXXXXXX')
  [[ $editor_runtime =~ ^/tmp/runcloud-previews\.[A-Za-z0-9]+$ ]] || fail 'Could not create a private editor runtime directory.'

  # Only per-session viewer URLs leave this terminal; CLI credentials stay here.
  printf '{}\n' >"$scratch/simulators.json"
  for platform in "${platforms[@]}"; do
    jq --arg platform "$platform" --slurpfile session "$scratch/$platform.json" \
      '.[$platform] = ($session[0].url | if type == "string" and length > 0 then . else null end)' \
      "$scratch/simulators.json" >"$scratch/simulators-next.json"
    mv -- "$scratch/simulators-next.json" "$scratch/simulators.json"
  done
  runcloud sandbox cp "$sandbox_id" "$scratch/simulators.json" ":$editor_runtime/simulators.json" >/dev/null
  guest 20 "chmod 600 '$editor_runtime/simulators.json'" >/dev/null
}

prepare_editor() {
  local editor_setup extension=runcloud.simulator-previews-0.1.0.vsix
  tar -xzf "$fixture_archive" -C "$scratch" "$extension"
  editor_install_dir=$(guest 20 'umask 077; mktemp -d /tmp/runcloud-code-server.XXXXXXXX')
  [[ $editor_install_dir =~ ^/tmp/runcloud-code-server\.[A-Za-z0-9]+$ ]] || fail 'Could not create an editor installation directory.'
  runcloud sandbox cp "$sandbox_id" "$scratch/$extension" ":$editor_install_dir/$extension" >/dev/null
  editor_setup=$(cat <<'GUEST'
set -eu
version=4.117.0
kilo_version=7.8.40
case $(uname -m) in
  x86_64)
    arch=amd64
    sha=5616650cc65a82046eb7ab24b794da6632a3292d07df06908800d75544962391
    kilo_arch=linux-x64
    kilo_sha=6dc1fd7c0bd7cc7eac35d00df05533a7654bb9e8a338f86be30d6e806e907325
    ;;
  aarch64)
    arch=arm64
    sha=70d376cd554403f45311de207f828f58ddd91f23df73afaf0eaa7e50987936a6
    kilo_arch=linux-arm64
    kilo_sha=38b6b15cf2c650772a25a6978dbe298d6dba2e054da4a973a49e7ddd92206b62
    ;;
  *) printf 'Unsupported code-server architecture\n' >&2; exit 1 ;;
esac

asset="code-server-$version-linux-$arch.tar.gz"
curl -fsSL "https://github.com/coder/code-server/releases/download/v$version/$asset" -o "$install_dir/$asset"
printf '%s  %s\n' "$sha" "$install_dir/$asset" | sha256sum --check --status
tar -xzf "$install_dir/$asset" --strip-components=1 -C "$install_dir"
rm "$install_dir/$asset"
kilo_asset="kilocode.kilo-code-$kilo_version@$kilo_arch.vsix"
curl -fsSL "https://open-vsx.org/api/kilocode/kilo-code/$kilo_arch/$kilo_version/file/$kilo_asset" -o "$install_dir/$kilo_asset"
printf '%s  %s\n' "$kilo_sha" "$install_dir/$kilo_asset" | sha256sum --check --status
"$install_dir/bin/code-server" --install-extension "$install_dir/$kilo_asset"
rm "$install_dir/$kilo_asset"
"$install_dir/bin/code-server" --install-extension "$install_dir/$preview_extension" --force
rm "$install_dir/$preview_extension"
GUEST
  )
  if ! guest 260 "install_dir='$editor_install_dir'; preview_extension='$extension'; $editor_setup" >"$scratch/editor-install.log" 2>&1; then
    log_failure "$scratch/editor-install.log" 'Could not install code-server, Kilo Code, and the simulator extension.'
    exit 1
  fi
}

start_editor() {
  local editor_start
  stage_previews
  editor_start=$(cat <<'GUEST'
nohup "$install_dir/bin/code-server" --bind-addr 127.0.0.1:8082 --auth none \
  --disable-telemetry --disable-proxy -- "$PWD" >"$install_dir/editor.log" 2>&1 </dev/null &
curl --retry 30 --retry-connrefused --retry-delay 1 --max-time 2 -fs \
  http://127.0.0.1:8082/healthz >/dev/null || {
    printf 'code-server failed its loopback health check\n' >&2
    exit 1
  }
GUEST
  )
  guest 45 "cd '$workspace' && install_dir='$editor_install_dir' && export RUNCLOUD_SIMULATORS_FILE='$editor_runtime/simulators.json' && $editor_start" || return
  # Metro's existing exposure enables the managed SSH transport. Only SSH can
  # reach the editor port, which is bound to guest loopback.
  runcloud sandbox setup-ssh "$sandbox_id" >/dev/null || return
  editor_socket_dir=$(mktemp -d) || return
  printf '%s\n' "$editor_socket_dir" >"$scratch/ssh-dir"
  ssh -fNT -M -S "$editor_socket_dir/control" -o BatchMode=yes -o ExitOnForwardFailure=yes \
    -o ConnectTimeout=15 -o LogLevel=ERROR -L 127.0.0.1:8082:127.0.0.1:8082 "$editor_ssh_host" 9>&- || return
  curl --max-time 15 -fsS http://127.0.0.1:8082/healthz >/dev/null || return
  printf 'Editor: http://127.0.0.1:8082/?folder=%s\n' "$workspace"
  printf 'Run “run.cloud: Show Simulators” from the editor Command Palette.\n'
}

stop_editor() {
  local directory
  if [[ -s $scratch/ssh-dir ]]; then
    directory=$(<"$scratch/ssh-dir")
    if [[ -d $directory && -O $directory && ! -L $directory ]]; then
      ssh -S "$directory/control" -O exit "$editor_ssh_host" >/dev/null 2>&1 || true
      rm -f -- "$directory/control"
      rmdir -- "$directory" || return 1
    fi
    rm -f -- "$scratch/ssh-dir"
  fi
  return 0
}

fetch_verified() {
  local url=$1 output=$2 checksum=$3
  curl --fail --silent --show-error --location --retry 2 "$url" --output "$output"
  printf '%s  %s\n' "$checksum" "$output" | sha256sum --check --status || fail "Checksum mismatch for ${output##*/}."
}

install_launcher() {
  local arch checksum
  install_tmp=$(mktemp -d)
  install_target=
  trap 'rm -rf -- "$install_tmp"; if [[ -n $install_target ]]; then rm -f -- "$install_target"; fi' EXIT
  mkdir -p -- "$bin_dir"
  if [[ -f ${BASH_SOURCE[0]} ]]; then
    cp -- "${BASH_SOURCE[0]}" "$install_tmp/cloud-ide"
  else
    curl -fsSL "$public_script" -o "$install_tmp/cloud-ide"
  fi
  bash -n "$install_tmp/cloud-ide"

  if ! command -v jq >/dev/null; then
    case $(uname -m) in
      x86_64) arch=amd64; checksum=020468de7539ce70ef1bceaf7cde2e8c4f2ca6c3afb84642aabc5c97d9fc2a0d ;;
      aarch64) arch=arm64; checksum=6bc62f25981328edd3cfcfe6fe51b073f2d7e7710d7ef7fcdac28d4e384fc3d4 ;;
      *) fail 'Install jq for this Linux architecture before continuing.' ;;
    esac
    fetch_verified "https://github.com/jqlang/jq/releases/download/jq-1.8.1/jq-linux-$arch" "$install_tmp/jq" "$checksum"
    install -m 755 -- "$install_tmp/jq" "$bin_dir/jq"
  fi

  local version
  version=$(runcloud --version 2>/dev/null || true)
  if [[ -z $version || $version == 0.1.* || ( $version =~ ^0\.2\.([0-9]+)$ && ${BASH_REMATCH[1]} -lt 247 ) ]]; then
    curl -fsSL https://run.cloud/install -o "$install_tmp/runcloud-install.sh"
    RUNCLOUD_NO_LOGIN=1 RUNCLOUD_INSTALL_DIR="$runcloud_home/bin" sh "$install_tmp/runcloud-install.sh"
  fi
  install_target=$(mktemp "$bin_dir/.cloud-ide.XXXXXXXX")
  install -m 755 -- "$install_tmp/cloud-ide" "$install_target"
  mv -f -- "$install_target" "$bin_dir/cloud-ide"
  install_target=
  if ! runcloud account --json >/dev/null 2>&1; then
    if ( : </dev/tty ) 2>/dev/null; then
      runcloud login </dev/tty >/dev/tty 2>/dev/tty
      runcloud account --json >/dev/null
    else
      printf 'Run runcloud login from an interactive terminal before starting the workspace.\n'
    fi
  fi
  printf 'Installed cloud-ide. Run these commands in your terminal:\n'
  printf "  export PATH=%q:\"\$PATH\"\n" "$bin_dir"
  printf '%s\n' '  cloud-ide up both --editor' '  cloud-ide down  # in a second terminal'
}

prepare_ios() {
  fetch_verified \
    https://github.com/expo/expo-go-releases/releases/download/Expo-Go-54.0.7/Expo-Go-54.0.7.tar.gz \
    "$scratch/expo-ios.tar.gz" b290828bdacd87a5bbbcfd193fdea6c446601cfe2bdd3a1cdcf604468f6ac416
  mkdir "$scratch/ExpoGo.app"
  # Expo's archive contains the bundle's files at its root.
  tar -xzf "$scratch/expo-ios.tar.gz" -C "$scratch/ExpoGo.app"
  tar -czf "$scratch/Expo-Go-ios.tar.gz" -C "$scratch" ExpoGo.app
  provision asset-ios asset push "$scratch/Expo-Go-ios.tar.gz" --name "$sandbox_name-ios"
}

prepare_android() {
  fetch_verified \
    https://github.com/expo/expo-go-releases/releases/download/Expo-Go-54.0.8/Expo-Go-54.0.8.apk \
    "$scratch/Expo-Go-android.apk" d72ed2cec15bf029c942d1cb70c933976ec83048e00d130bbfa6bad8cf22331a
  provision asset-android asset push "$scratch/Expo-Go-android.apk" --name "$sandbox_name-android"
}

is_demo() {
  [[ -f "$1/App.js" && -f "$1/app.json" && -f "$1/package-lock.json" ]] &&
    jq -e '.name == "react-native-cloud-dev-example"' "$1/package.json" >/dev/null 2>&1
}

load_fixture() {
  if [[ -n $fixture_archive ]]; then return; fi
  local fixture=react-native-cloud-project.tgz
  local checksum=7e4ae76d26c34a3ff63e05f818e6b7e238fc23cd74323483259d0818790c8550
  local beside_script
  beside_script=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/$fixture
  if [[ -f $beside_script ]]; then
    printf '%s  %s\n' "$checksum" "$beside_script" | sha256sum --check --status || fail 'Workspace archive checksum mismatch.'
    fixture_archive=$beside_script
  else
    fetch_verified "https://run.cloud/examples/$fixture" "$scratch/$fixture" "$checksum"
    fixture_archive="$scratch/$fixture"
  fi
}

prepare_demo() {
  project=$PWD
  if is_demo "$project"; then return; fi
  project="$PWD/cloud-counter"
  if is_demo "$project"; then return; fi
  [[ ! -e $project ]] || fail "Move or rename the existing $project before starting."
  load_fixture
  mkdir "$project"
  tar -xzf "$fixture_archive" -C "$project" App.js app.json package.json package-lock.json
}

case $action in
  install) install_launcher; exit 0 ;;
  down) stop_workspace; exit 0 ;;
esac
open_state
flock -n 9 || fail 'A Cloud IDE workspace is already running. Use cloud-ide down first.'
[[ -z $(active_workspace) ]] || fail 'A previous workspace still has state. Run cloud-ide down to recover it.'
scratch=$(mktemp -d "$state_root/workspace.XXXXXXXX")
printf '%s\n' "$sandbox_name" >"$scratch/name"
printf '%s\n' "$PWD" >"$scratch/export-dir"
use_workspace "$scratch"
if $editor || [[ -n $repo ]]; then touch "$scratch/remote-edit"; fi
printf '%s\n' "${scratch##*/}" >"$state_root/active"
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM

if ! runcloud account --json >"$scratch/account.json" 2>"$scratch/account.error"; then
  log_failure "$scratch/account.error" 'Run runcloud login and check runcloud account.'
  exit 1
fi
if [[ -z $repo ]]; then prepare_demo; fi
if $editor; then load_fixture; fi
checkpoint
for platform in "${platforms[@]}"; do
  printf 'Preparing Expo Go for %s\n' "$platform"
  "prepare_$platform"
done

printf 'Starting the Linux workspace\n'
sandbox_started=$SECONDS
memory=4096
if $editor; then memory=8192; fi
provision sandbox sandbox create --image runcloud/agent-base --name "$sandbox_name" \
  --cpu 2 --memory "$memory" --disk 12 --idle-pause 0 --timeout 1200 --expose 8081 --no-secrets
sandbox_id=$(receipt sandbox)
metro_host=$(jq -er '.box.hostname' "$scratch/sandbox.json") || fail 'The sandbox response did not include a Metro hostname.'
[[ $metro_host == "$sandbox_name-box.run.cloud" ]] || fail 'Unexpected Metro hostname in the sandbox response.'
printf 'Sandbox %s\n' "$sandbox_id"
deadline=$((sandbox_started + 1200))

printf 'Installing workspace dependencies\n'
if [[ -n $repo ]]; then
  if [[ -n $ref ]]; then
    guest 120 "git init -q '$workspace' && cd '$workspace' && git remote add origin '$repo' && git fetch --depth 1 origin '$ref' && git checkout --detach FETCH_HEAD" >"$scratch/git.log" 2>&1 || fail 'Could not fetch the requested public Git revision.'
  else
    guest 120 "git clone --depth 1 '$repo' '$workspace'" >"$scratch/git.log" 2>&1 || fail 'Could not clone the public Git repository.'
  fi
  runcloud sandbox cp "$sandbox_id" ":$workspace/package-lock.json" "$scratch/checkout-lock.json" >/dev/null 2>&1 || fail 'The checkout must contain package-lock.json.'
  jq -e '.packages["node_modules/expo"].version | startswith("54.")' "$scratch/checkout-lock.json" >/dev/null || fail 'The checkout must use Expo SDK 54.'
else
  guest 20 "mkdir -p '$workspace'" >/dev/null
  for file in app.json package.json package-lock.json; do
    runcloud sandbox cp "$sandbox_id" "$project/$file" ":$workspace/$file" >/dev/null
  done
  cp "$project/App.js" "$scratch/synced.js"
  runcloud sandbox cp "$sandbox_id" "$scratch/synced.js" ":$workspace/App.js" >/dev/null
fi

if ! guest 360 "cd '$workspace' && npm ci --no-audit --no-fund" >"$scratch/npm.log" 2>&1; then
  log_failure "$scratch/npm.log" 'npm ci failed inside the sandbox.'
  exit 1
fi
checkpoint
# Metro needs its file watcher. CI mode disables watching.
guest 20 "cd '$workspace' && unset CI && EXPO_PACKAGER_PROXY_URL='https://$metro_host' nohup ./node_modules/.bin/expo start --go --lan --port 8081 >/tmp/cloud-counter-metro.log 2>&1 </dev/null &" >"$scratch/metro-start.log" 2>&1 || fail 'Could not start Metro.'
if [[ $(curl --silent --fail --retry 25 --retry-delay 1 --retry-all-errors --max-time 3 "https://$metro_host/status" 2>"$scratch/metro-status.error") != packager-status:running ]]; then
  guest 10 'tail -n 10 /tmp/cloud-counter-metro.log' >"$scratch/metro.log" 2>&1 || true
  log_failure "$scratch/metro.log" 'Metro did not report ready at the workspace hostname.'
  exit 1
fi
checkpoint

if $editor; then
  printf 'Installing code-server and its extensions\n'
  prepare_editor
fi
checkpoint

for platform in "${platforms[@]}"; do
  printf 'Starting the %s device\n' "$platform"
  device_started=$SECONDS
  provision "$platform" "$platform" create --install-asset "$(receipt "asset-$platform")" \
    --display-name "Cloud Counter · $platform" --inactivity-timeout none --hard-timeout 12m
  session_id=$(receipt "$platform")
  runcloud "$platform" open-url "exps://$metro_host" --id "$session_id" --json >"$scratch/open-$platform.json" 2>"$scratch/open-$platform.error" || fail "Expo Go could not open Metro on $platform."
  printf 'Open Cloud Counter · %s in the run.cloud dashboard (%s)\n' "$platform" "$session_id"
  if (( device_started + 720 < deadline )); then deadline=$((device_started + 720)); fi
done

touch "$scratch/ready"
if $editor; then
  start_editor
elif [[ -n $repo ]]; then
  printf 'Edit in %s using runcloud sandbox shell %s\n' "$workspace" "$sandbox_id"
else
  printf 'Save %s/App.js to sync it to the workspace.\n' "$project"
fi
printf 'Press Ctrl-C to stop, or run cloud-ide down from another terminal.\n'

while (( SECONDS < deadline )); do
  sleep 1
  checkpoint
  if [[ -e $scratch/remote-edit ]]; then continue; fi
  if [[ ! -f $project/App.js ]] || cmp -s "$project/App.js" "$scratch/synced.js"; then continue; fi
  cp "$project/App.js" "$scratch/app-next.js"
  runcloud sandbox cp "$sandbox_id" "$scratch/app-next.js" ":$workspace/.App.js.next" >/dev/null
  guest 20 "mv -f '$workspace/.App.js.next' '$workspace/App.js'" >/dev/null
  mv "$scratch/app-next.js" "$scratch/synced.js"
  printf 'Synced App.js\n'
done
