#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
IMAGE="${FLUTTER_DOCKER_IMAGE:-ghcr.io/cirruslabs/flutter:stable}"
ADB_KEY_DIR="$ROOT_DIR/.android-adb"
CACHE_ROOT="${FLUTTER_DOCKER_CACHE_ROOT:-$ROOT_DIR/.docker-cache/flutter}"
GRADLE_CACHE_DIR="$CACHE_ROOT/gradle"
PUB_CACHE_DIR="$CACHE_ROOT/pub"
ANDROID_LICENSES_DIR="$CACHE_ROOT/android-sdk/licenses"
ANDROID_NDK_DIR="$CACHE_ROOT/android-sdk/ndk"
ANDROID_CMAKE_DIR="$CACHE_ROOT/android-sdk/cmake"
MODE="${1:-flutter}"
if [ "$#" -gt 0 ]; then
  shift || true
fi

DOCKER_ENV_ARGS=()
if [ -n "${ADB_SERVER_SOCKET:-}" ]; then
  DOCKER_ENV_ARGS+=("-e" "ADB_SERVER_SOCKET=${ADB_SERVER_SOCKET}")
fi
if [ -n "${TDC114_ADB_CONNECT_ADDRESS:-}" ]; then
  DOCKER_ENV_ARGS+=("-e" "TDC114_ADB_CONNECT_ADDRESS=${TDC114_ADB_CONNECT_ADDRESS}")
fi

mkdir -p "$ADB_KEY_DIR"
mkdir -p "$GRADLE_CACHE_DIR"
mkdir -p "$PUB_CACHE_DIR"
mkdir -p "$ANDROID_LICENSES_DIR"
mkdir -p "$ANDROID_NDK_DIR"
mkdir -p "$ANDROID_CMAKE_DIR"

docker run --rm \
  -u 0:0 \
  "${DOCKER_ENV_ARGS[@]}" \
  -v "$ROOT_DIR:/workspace" \
  -v "$ADB_KEY_DIR:/root/.android" \
  -v "$GRADLE_CACHE_DIR:/root/.gradle" \
  -v "$PUB_CACHE_DIR:/root/.pub-cache" \
  -v "$ANDROID_LICENSES_DIR:/opt/android-sdk-linux/licenses" \
  -v "$ANDROID_NDK_DIR:/opt/android-sdk-linux/ndk" \
  -v "$ANDROID_CMAKE_DIR:/opt/android-sdk-linux/cmake" \
  -w /workspace/app \
  "$IMAGE" \
  sh -lc '
    set -e
    if command -v sdkmanager >/dev/null 2>&1; then
      yes | sdkmanager --licenses >/tmp/android-sdk-licenses.log 2>&1 || {
        cat /tmp/android-sdk-licenses.log >&2
        exit 1
      }
    fi
    if [ -n "${TDC114_ADB_CONNECT_ADDRESS:-}" ]; then
      adb connect "$TDC114_ADB_CONNECT_ADDRESS" || true
      adb devices
    fi
    if [ "$1" = "adb-devices" ]; then
      exit 0
    fi
    if [ "$1" = "adb" ]; then
      shift
      exec adb "$@"
    fi
    flutter pub get
    flutter "$@"
    chown -R 1000:1000 /workspace/app
  ' sh "$MODE" "$@"
