#!/usr/bin/env bash
# highwind-run: builds an app, installs it on an iOS simulator or an Android device, launches it and
# shows its output until the app exits. Highwind installs it as ~/.highwind/bin/highwind-run and uses it as
# the run command of an Xcode or Gradle project's service, so the project needs no script of
# its own. Highwind boots the device before the command runs and shows it in a pane, because the
# command names it with --udid or --device.
#
#   highwind-run ios --udid <simulator UDID> [--workspace <x.xcworkspace> | --project <x.xcodeproj>]
#                [--scheme <scheme>] [--configuration <Debug>]
#   highwind-run android --device <AVD name or adb serial> [--project <folder with gradlew>]
#                [--module <app>] [--variant <Debug>]
#
# Paths are relative to the current folder. Whatever isn't given is looked up: the workspace or
# project, the scheme named like it, the Gradle module that builds an app.
#
# Written for the bash 3.2 that macOS ships.
set -euo pipefail

fail() {
    echo "highwind-run: $*" >&2
    exit 1
}

step() {
    printf '\033[1m▸ %s\033[0m\n' "$*"
}

# Drops compiler and linker warnings from build output, which can run to
# thousands of lines, and prints how many there were. With pipefail the
# pipeline keeps the build's exit status.
hide_warnings() {
    awk '/warning: / { n++; next } { print; fflush() }
        END { if (n) printf "%d build warning%s not shown\n", n, (n == 1 ? "" : "s") }'
}

usage() {
    sed -n '8,12p' "$0" | sed 's/^# \{0,1\}//'
    exit 2
}

# Tells Highwind this command booted a device, so it shuts the device down like one it booted itself.
record_started() {
    mkdir -p "$HOME/.highwind"
    printf '%s\t%s\n' "$1" "$2" >> "$HOME/.highwind/started-devices"
}

# MARK: - iOS

run_ios() {
    local udid="" workspace="" project="" scheme="" configuration="Debug"
    while [ $# -gt 0 ]; do
        case "$1" in
            --udid) udid="${2:-}"; shift 2 ;;
            --workspace) workspace="${2:-}"; shift 2 ;;
            --project) project="${2:-}"; shift 2 ;;
            --scheme) scheme="${2:-}"; shift 2 ;;
            --configuration) configuration="${2:-}"; shift 2 ;;
            *) fail "unknown option $1" ;;
        esac
    done
    [ -n "$udid" ] || fail "--udid <simulator UDID> is required (xcrun simctl list devices lists them)"

    if [ -z "$workspace" ] && [ -z "$project" ]; then
        # A workspace when there is one (CocoaPods, Flutter), else the project. Workspaces
        # inside a project package are Xcode's own.
        workspace="$(find . -maxdepth 3 -name '*.xcworkspace' -not -path '*.xcodeproj/*' \
            -not -path '*/Pods/*' -not -path '*/node_modules/*' -not -path '*/build/*' | sort | head -1)"
        if [ -z "$workspace" ]; then
            project="$(find . -maxdepth 3 -name '*.xcodeproj' -not -path '*/Pods/*' \
                -not -path '*/node_modules/*' -not -path '*/build/*' | sort | head -1)"
        fi
        [ -n "$workspace$project" ] || fail "no Xcode workspace or project in $(pwd)"
    fi
    local kind container
    if [ -n "$workspace" ]; then
        kind="workspace"; container="$workspace"
    else
        kind="project"; container="$project"
    fi

    if [ -z "$scheme" ]; then
        scheme="$(ios_scheme "$kind" "$container")"
        [ -n "$scheme" ] || fail "$container has no schemes; pass --scheme"
    fi

    step "Booting the simulator"
    case "$(xcrun simctl list devices)" in
        *"($udid) (Shutdown)"*) record_started ios "$udid" ;;
    esac
    xcrun simctl bootstatus "$udid" -b >/dev/null

    step "Building $scheme"
    xcodebuild build -"$kind" "$container" -scheme "$scheme" -configuration "$configuration" \
        -destination "id=$udid" -quiet 2>&1 | hide_warnings

    # The app the scheme builds: the first target whose product is an .app.
    local settings app bundle_id
    settings="$(xcodebuild -showBuildSettings -"$kind" "$container" -scheme "$scheme" \
        -configuration "$configuration" -destination "id=$udid" 2>/dev/null)"
    app="$(printf '%s\n' "$settings" | awk '
        /^Build settings for / { dir = ""; name = ""; ext = ""; id = "" }
        $1 == "TARGET_BUILD_DIR" { sub(/^[^=]*= /, ""); dir = $0 }
        $1 == "WRAPPER_NAME" { sub(/^[^=]*= /, ""); name = $0 }
        $1 == "WRAPPER_EXTENSION" { sub(/^[^=]*= /, ""); ext = $0 }
        $1 == "PRODUCT_BUNDLE_IDENTIFIER" { sub(/^[^=]*= /, ""); id = $0 }
        dir != "" && name != "" && ext == "app" && id != "" { print dir "/" name "\t" id; exit }
    ')"
    [ -n "$app" ] || fail "the $scheme scheme builds no app"
    bundle_id="${app#*	}"
    app="${app%%	*}"

    step "Installing $(basename "$app")"
    xcrun simctl install "$udid" "$app"

    step "Launching $bundle_id"
    # Shows the app's stdout and stderr until it exits, and passes a stop on to the app.
    exec xcrun simctl launch --console-pty --terminate-running-process "$udid" "$bundle_id"
}

# The scheme to build when none is given.
ios_scheme() {
    local kind="$1" container="$2" name output list
    name="$(basename "$container")"
    name="${name%.*}"
    if ! output="$(xcodebuild -list -"$kind" "$container" 2>&1)"; then
        printf '%s\n' "$output" | grep -E 'error:|Reason:' >&2 || true
        fail "xcodebuild can't read $container"
    fi
    list="$(printf '%s\n' "$output" | awk '
        /^ *Schemes:/ { on = 1; next }
        on && /^ *$/ { exit }
        on { sub(/^ +/, ""); print }
    ')"
    # Named like the container, then its iOS variant (Breeze-iOS), then any iOS one, then the first.
    local scheme
    scheme="$(printf '%s\n' "$list" | grep -xF "$name" | head -1 || true)"
    [ -n "$scheme" ] || scheme="$(printf '%s\n' "$list" | grep -ixE "$name[-_ ]?ios" | head -1 || true)"
    [ -n "$scheme" ] || scheme="$(printf '%s\n' "$list" | grep -i 'ios' | head -1 || true)"
    [ -n "$scheme" ] || scheme="$(printf '%s\n' "$list" | head -1)"
    echo "$scheme"
}

# MARK: - Android

run_android() {
    local device="" project="" module="" variant="Debug"
    while [ $# -gt 0 ]; do
        case "$1" in
            --device) device="${2:-}"; shift 2 ;;
            --project) project="${2:-}"; shift 2 ;;
            --module) module="${2:-}"; shift 2 ;;
            --variant) variant="${2:-}"; shift 2 ;;
            *) fail "unknown option $1" ;;
        esac
    done
    [ -n "$device" ] || fail "--device <AVD name or adb serial> is required"

    if [ -z "$project" ]; then
        if [ -x ./gradlew ]; then
            project="."
        else
            project="$(find . -maxdepth 2 -name gradlew -not -path '*/node_modules/*' | sort | head -1)"
            [ -n "$project" ] || fail "no Gradle project (gradlew) in $(pwd)"
            project="$(dirname "$project")"
        fi
    fi
    cd "$project"

    local sdk adb
    sdk="$(android_sdk)"
    [ -n "$sdk" ] || fail "no Android SDK found; set ANDROID_HOME"
    adb="$sdk/platform-tools/adb"
    [ -x "$adb" ] || adb="$(command -v adb || true)"
    [ -n "$adb" ] || fail "adb isn't installed in $sdk/platform-tools"

    if [ -z "$module" ]; then
        module="$(android_module)"
        [ -n "$module" ] || fail "no module applies the Android application plugin; pass --module"
    fi

    # Gradle needs Java 17 or later; Android Studio's own runtime when nothing else is set.
    if [ -z "${JAVA_HOME:-}" ] && [ -d "/Applications/Android Studio.app/Contents/jbr/Contents/Home" ]; then
        export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home"
    fi

    local serial
    serial="$(android_serial "$adb" "$device")"
    if [ -z "$serial" ]; then
        local emulator="$sdk/emulator/emulator"
        [ -x "$emulator" ] || fail "$device isn't connected, and there's no emulator to start it with"
        step "Starting emulator $device"
        # A snapshot saved in software rendering, as Highwind's own emulators did without a window,
        # comes up white on the Mac's GPU. A cold boot saves a new one.
        local snapshot_load=()
        local snapshot_gpu
        snapshot_gpu="$(sed -n 's/^hw\.gpu\.mode *= *//p' "$HOME/.android/avd/$device.avd/snapshots/default_boot/hardware.ini" 2>/dev/null | tr -d '\r')"
        if [ -n "$snapshot_gpu" ] && [ "$snapshot_gpu" != "host" ]; then snapshot_load=(-no-snapshot-load); fi
        # In its own session, so stopping this command doesn't take the emulator with it.
        perl -MPOSIX=setsid -e 'setsid; exec @ARGV' "$emulator" -avd "$device" -no-boot-anim \
            ${snapshot_load[@]+"${snapshot_load[@]}"} >/dev/null 2>&1 &
        record_started android "$device"
        local tries=0
        while [ -z "$serial" ]; do
            tries=$((tries + 1))
            [ $tries -le 90 ] || fail "emulator $device didn't start within 3 minutes"
            sleep 2
            serial="$(android_serial "$adb" "$device")"
        done
    fi
    # Gradle reads this. The adb calls name the device too, which is how Highwind sees it's in use.
    export ANDROID_SERIAL="$serial"

    step "Waiting for $device to finish booting"
    "$adb" -s "$serial" wait-for-device
    until [ "$("$adb" -s "$serial" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = "1" ]; do
        sleep 2
    done

    local task=":${module//\//:}:install$variant"
    step "Building and installing ($task)"
    ./gradlew --console=plain -q "$task"

    # The package and its launcher activity, from the APK Gradle just installed.
    local apk aapt2 badging package activity
    apk="$(find "$module/build/outputs/apk" -name '*.apk' -print0 2>/dev/null | xargs -0 ls -t 2>/dev/null | head -1)"
    [ -n "$apk" ] || fail "no APK under $module/build/outputs/apk"
    aapt2="$(ls -d "$sdk"/build-tools/*/aapt2 2>/dev/null | grep -v -- '-rc' | sort -V | tail -1)"
    [ -n "$aapt2" ] || fail "aapt2 isn't installed; add Android SDK Build-Tools in Android Studio's SDK Manager"
    badging="$("$aapt2" dump badging "$apk" 2>/dev/null)"
    package="$(printf '%s\n' "$badging" | sed -n "s/^package: name='\([^']*\)'.*/\1/p" | head -1)"
    activity="$(printf '%s\n' "$badging" | sed -n "s/^launchable-activity: name='\([^']*\)'.*/\1/p" | head -1)"
    [ -n "$package" ] || fail "couldn't read the package name from $apk"
    [ -n "$activity" ] || fail "$package has no launcher activity"

    step "Launching $package"
    "$adb" -s "$serial" shell am force-stop "$package"
    "$adb" -s "$serial" shell am start -W -n "$package/$activity" >/dev/null

    local pid="" tries=0
    while [ -z "$pid" ]; do
        tries=$((tries + 1))
        [ $tries -le 30 ] || fail "$package didn't start; its crash log: $adb -s $serial logcat -d -b crash"
        sleep 1
        pid="$("$adb" -s "$serial" shell pidof -s "$package" 2>/dev/null | tr -d '\r' || true)"
    done

    # The app's log from now on, until the app exits. Stopping this command stops the app, as
    # it does on iOS.
    "$adb" -s "$serial" logcat --pid="$pid" -T 1 -v color &
    local logcat=$!
    trap 'kill $logcat 2>/dev/null || true' EXIT
    trap '"$adb" -s "$serial" shell am force-stop "$package" >/dev/null 2>&1 || true; exit 143' TERM INT HUP
    while kill -0 "$logcat" 2>/dev/null \
        && [ "$("$adb" -s "$serial" shell pidof -s "$package" 2>/dev/null | tr -d '\r' || true)" = "$pid" ]; do
        sleep 2
    done
    step "$package exited"
}

android_sdk() {
    local candidate
    for candidate in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" \
        "$(sed -n 's/^sdk\.dir=//p' local.properties 2>/dev/null)" "$HOME/Library/Android/sdk"; do
        if [ -n "$candidate" ] && [ -d "$candidate/platform-tools" ]; then
            echo "$candidate"
            return
        fi
    done
}

# The module whose build file applies the application plugin, `app` first; the root build file
# only declares it.
android_module() {
    local file dir found=""
    for file in app/build.gradle.kts app/build.gradle */build.gradle.kts */build.gradle \
        */*/build.gradle.kts */*/build.gradle; do
        [ -f "$file" ] || continue
        if grep -v 'apply false' "$file" | grep -qE 'com\.android\.application|android\.application'; then
            dir="$(dirname "$file")"
            found="$dir"
            break
        fi
    done
    echo "$found"
}

# The adb serial for a serial or an AVD name; empty when that device isn't running.
android_serial() {
    local adb="$1" device="$2" serial
    if "$adb" devices | awk -v d="$device" '$1 == d && $2 == "device" { f = 1 } END { exit !f }'; then
        echo "$device"
        return
    fi
    for serial in $("$adb" devices | awk '/^emulator-[0-9]+\tdevice$/ { print $1 }'); do
        if [ "$("$adb" -s "$serial" emu avd name 2>/dev/null | head -1 | tr -d '\r')" = "$device" ]; then
            echo "$serial"
            return
        fi
    done
}

# MARK: -

case "${1:-}" in
    ios) shift; run_ios "$@" ;;
    android) shift; run_android "$@" ;;
    *) usage ;;
esac
