
# --- build progress reporting --------------------------------------------------
# This project was generated by the Codename One Initializr. When you run this
# launcher it tells cloud.codenameone.com that a build started and how Maven
# exited, so a first build that dies on this machine (no JDK, an old JDK, a
# Maven download, a compile error, a sign-in that timed out, a build that was
# never submitted) is visible to us
# instead of silent, and we can fix what trips people up.
#
# It sends ONLY: a one-way SHA-256 hash of this project's package name (never
# the name itself), the target (e.g. javascript_cloud), the OS family, the Java
# major version, the exit code, one word for why the build stopped and how many
# seconds it took. Never your code, paths, user name or build output. Each
# report is a single request with a 3 second limit; a failure is ignored and
# never changes the build's output or exit code.
#
# Opt out with CN1_TELEMETRY=0, e.g.  CN1_TELEMETRY=0 ./build.sh javascript_cloud
# or  export CN1_TELEMETRY=0  in your shell profile.
CN1_PROJECT_ID="__CN1_PROJECT_ID__"
CN1_MIN_JAVA="__CN1_MIN_JAVA__"
CN1_EVENTS_URL="${CN1_EVENTS_URL:-https://cloud.codenameone.com/api/v2/funnel/initializr-event}"
# Maven reports IDE builds itself (cn1.telemetry.* in pom.xml); this tells it the
# launcher is already reporting this one, so it is counted once.
export CN1_LAUNCHER=1

function cn1_event {
  [ "${CN1_TELEMETRY:-1}" = "0" ] && return 0
  command -v curl >/dev/null 2>&1 || return 0
  curl -s -o /dev/null -m 3 -X POST "$CN1_EVENTS_URL" \
    --data-urlencode "pkg=$CN1_PROJECT_ID" "$@" >/dev/null 2>&1 || true
}

function cn1_os {
  case "$(uname -s 2>/dev/null)" in
    Darwin) echo mac ;;
    Linux) if grep -qi microsoft /proc/version 2>/dev/null; then echo wsl; else echo linux; fi ;;
    MINGW*|MSYS*|CYGWIN*) echo windows ;;
    *) echo other ;;
  esac
}

function cn1_java_major {
  local java="java"
  [ -n "${JAVA_HOME-}" ] && java="$JAVA_HOME/bin/java"
  local v
  v="$("$java" -version 2>&1 | sed -n 's/.*version "\([^"]*\)".*/\1/p' | head -n 1)" || true
  if [ -z "$v" ]; then echo none; return; fi
  case "$v" in
    1.*) v="${v#1.}" ;;
  esac
  v="${v%%[!0-9]*}"
  echo "${v:-unknown}"
}

# One word for why the build stopped, matched against Maven's and the build
# client's own output. Order matters: TLS failures surface inside Maven's
# "Could not transfer artifact", so they are checked before downloads, and the
# build client's specific refusals before the generic BUILD FAILURE. When the
# output says nothing specific, the Java found before the build decides: no
# JDK at all, or one older than this project's Java level.
#
# A clean exit is not always a submitted build: the build client returns
# normally from the free plan's size limit, and a cloud build that started
# sending but never confirmed did not reach the build server either. Those are
# reported as such instead of "ok".
function cn1_reason {
  local code="$1" log="$2" java="$3"
  if [ "$code" = "0" ]; then
    # No copy of the output (no temp file could be made, or a tee could not
    # write all of it and removed it): a clean exit cannot be told from
    # size_limit or not_submitted, so it is not claimed as ok.
    if [ -z "$log" ] || [ ! -f "$log" ]; then echo unknown; return; fi
    if grep -qE "Jar size limit reached|Quota size limit reached" "$log"; then echo size_limit
    elif grep -q "Sending build request to the server" "$log" && ! grep -q "Your build was submitted" "$log"; then echo not_submitted
    else echo ok
    fi
    return
  fi
  { [ -z "$log" ] || [ ! -f "$log" ]; } && log=/dev/null
  if grep -qE "JAVA_HOME environment variable is not defined correctly|java/javac command does not exist|No compiler is provided in this environment" "$log"; then echo no_jdk
  elif grep -qE "invalid target release|release version [0-9]+ not supported|UnsupportedClassVersionError|class file version" "$log"; then echo java_too_old
  elif grep -qE "Browser login timed out" "$log"; then echo login_timeout
  elif grep -qE "Browser login failed|Could not complete browser login|Cannot authenticate a non-interactive build|Account login failed" "$log"; then echo login_failed
  elif grep -qE "COMPILATION ERROR" "$log"; then echo compile
  elif grep -qE "PKIX path building failed|unable to find valid certification path|SSLHandshakeException" "$log"; then echo tls
  elif grep -qE "Could not resolve dependencies|Could not transfer artifact|Could not download|Could not find artifact|Could not resolve plugin|PluginResolutionException|Non-resolvable parent POM|UnknownHostException|Connection timed out|Failed to fetch" "$log"; then echo maven_download
  elif grep -qE "Jar size limit reached|Quota size limit reached|exceeds 50MB in size|exceeds 100MB in size" "$log"; then echo size_limit
  elif grep -qE "certificate from Apple with the appropriate password is required|App id for an iOS build MUST be defined|Error reading the certificate file|Error reading the provisioning profile" "$log"; then echo no_certificate
  elif grep -qE "can't be empty|The icon must be a 512x512|Error reading the icon" "$log"; then echo project_config
  elif grep -qE "Error connecting to s3|Failed to upload to server|General network error occured" "$log"; then echo upload_failed
  elif grep -qE "Server Detailed Error Message|Error! Server response code" "$log"; then echo server_refused
  elif [ "$java" = "none" ]; then echo no_jdk
  elif [ -n "$java" ] && [ -z "${java//[0-9]/}" ] && [ "$java" -lt "$CN1_MIN_JAVA" ]; then echo java_too_old
  elif grep -qE "BUILD FAILURE" "$log"; then echo build_failed
  else echo unknown
  fi
}

# The direct children of a process. pgrep where it exists (macOS, any Linux
# with procps); otherwise the parent pid read from /proc/<pid>/stat, so a slim
# Linux container without procps still finds Maven under the launcher.
function cn1_children {
  if command -v pgrep >/dev/null 2>&1; then
    pgrep -P "$1" 2>/dev/null
    return 0
  fi
  local stat rest state ppid pid
  for stat in /proc/[0-9]*/stat; do
    rest="$(cat "$stat" 2>/dev/null)" || continue
    # Field 2 is the command name in parentheses and may contain spaces, so
    # read the fields after its closing ")": state, then the parent pid.
    rest="${rest##*) }"
    read -r state ppid _ <<< "$rest"
    if [ "$ppid" = "$1" ]; then
      pid="${stat#/proc/}"
      echo "${pid%/stat}"
    fi
  done
}

# Stops a process AND everything it started, children first. Killing only the
# parent left its children -- the curl/unzip of a first run's Maven download, a
# forked JVM -- running after the launcher reported the build as cancelled.
function cn1_kill_tree {
  [ -z "$1" ] && return 0
  local child
  for child in $(cn1_children "$1"); do
    cn1_kill_tree "$child"
  done
  kill -TERM "$1" 2>/dev/null || true
}

# Runs ./mvnw exactly as before, with the output still on your terminal, and
# reports how it ended.
function cn1_mvnw {
  # Opted out: no wrapper at all, Maven runs exactly as in any other project.
  if [ "${CN1_TELEMETRY:-1}" = "0" ]; then
    ./mvnw "$@"
    return $?
  fi
  local target="${CMD:-unknown}" os java start log code pipe_pid
  os="$(cn1_os)"
  java="$(cn1_java_major)"
  start="$(date +%s)"
  cn1_event --data-urlencode "step=launch" --data-urlencode "target=$target" \
    --data-urlencode "os=$os" --data-urlencode "java=$java" &
  # A copy of Maven's output, read only for the one-word reason. Nothing else
  # touches the disk: if no temp file can be created (TMPDIR missing, read-only
  # or full), Maven runs without the copy and the reason is just "unknown".
  log="$(mktemp 2>/dev/null)" || log=""
  if [ -n "$log" ] && ! : > "$log" 2>/dev/null; then
    log=""
  fi
  # Ctrl+C or a kill while Maven runs must still report how the run ended: a
  # developer who gave up on a hung download or a sign-in that never came
  # otherwise looks like one whose run never finished. Maven runs in a
  # BACKGROUND subshell the script waits for, because bash defers a trap until
  # a foreground command returns -- a `kill` aimed at this script alone would
  # otherwise wait for a hung Maven forever. The trap stops that subshell and
  # everything under it (Maven included), then reports and exits with the
  # signal's own status: 130 for Ctrl+C (SIGINT), 143 for SIGTERM.
  function cn1_on_signal {
    # A signal can land after the background subshell forked but before
    # `pipe_pid=$!` ran; $! already names it then. An empty pid would kill
    # nothing and turn the wait below into a wait for every child, Maven too.
    pipe_pid="${pipe_pid:-$!}"
    cn1_kill_tree "$pipe_pid"
    wait "$pipe_pid" 2>/dev/null
    cn1_event --data-urlencode "step=exit" --data-urlencode "target=$target" \
      --data-urlencode "os=$os" --data-urlencode "java=$java" --data-urlencode "exit=$1" \
      --data-urlencode "reason=interrupted" --data-urlencode "secs=$(( $(date +%s) - start ))"
    [ -n "$log" ] && rm -f "$log"
    trap - INT TERM
    exit "$1"
  }
  trap 'cn1_on_signal 130' INT
  trap 'cn1_on_signal 143' TERM
  set +e
  # The subshell exits with Maven's own status (PIPESTATUS[0]), so wait returns
  # exactly what Maven returned: a tee that fails (a full disk) cannot change
  # it, and no status file is needed. stdout and stderr stay separate -- each
  # is copied to the log by its own tee and passed through on its own channel,
  # so redirecting one still shows the other. stdin is redirected ON the
  # background subshell itself: bash gives an asynchronous command /dev/null
  # as stdin unless that command carries its own redirection, so a `<&0`
  # inside it would only duplicate /dev/null and a Maven prompt would read EOF.
  if [ -n "$log" ]; then
    # A tee that cannot write the whole copy (a disk that fills) removes it:
    # a partial copy could be missing the very line that decides the reason.
    ( ./mvnw "$@" 2> >(tee -a "$log" >&2 || rm -f "$log") | { tee -a "$log" || rm -f "$log"; }
      exit "${PIPESTATUS[0]}" ) <&0 &
  else
    ( ./mvnw "$@" ) <&0 &
  fi
  pipe_pid=$!
  wait "$pipe_pid"
  code=$?
  set -e
  trap - INT TERM
  cn1_event --data-urlencode "step=exit" --data-urlencode "target=$target" \
    --data-urlencode "os=$os" --data-urlencode "java=$java" --data-urlencode "exit=$code" \
    --data-urlencode "reason=$(cn1_reason "$code" "$log" "$java")" \
    --data-urlencode "secs=$(( $(date +%s) - start ))"
  if [ -n "$log" ]; then
    rm -f "$log"
  fi
  return "$code"
}
