#!/bin/bash
set -u

DEVICES_LIST="$(adb devices -l)"
echo "${DEVICES_LIST}"

LOG_ROOT="log_capture/session_stats/"
CRASH_ROOT="log_capture/crash_reports/"
CLEAN_LOGS="no"

pull_dir() {
  local serial="$1"
  local remote_subdir="$2"
  local local_base="$3"
  local local_path="${local_base}/${serial}/${remote_subdir}/"

  mapfile -t FILES < <(adb -s "${serial}" shell run-as com.foxx.androidcast ls "files/${remote_subdir}/" </dev/null \
    | tr -d '\r' | grep -v '^$' || true)

  if ((${#FILES[@]} == 0)); then
    echo "  (no files in files/${remote_subdir}/ on ${serial})"
    return 0
  fi

  mkdir -p "${local_path}"
  for f in "${FILES[@]}"; do
    adb -s "${serial}" exec-out run-as com.foxx.androidcast cat "files/${remote_subdir}/${f}" </dev/null \
      > "${local_path}/${f}"
    if [[ "${CLEAN_LOGS}" == "yes" ]]; then
      adb -s "${serial}" shell run-as com.foxx.androidcast rm -f "files/${remote_subdir}/${f}" </dev/null
    fi
  done
  echo "  pulled ${#FILES[@]} file(s) -> ${local_path}"
}

while true; do
  yn=""
  read -rp "clean logs on device after fetch? [y/N] " yn
  yn="${yn,,}"
  case "${yn}" in
    y|yes)
      CLEAN_LOGS="yes"
      break
      ;;
    n|no)
      break
      ;;
    "")
      CLEAN_LOGS="no"
      break
      ;;
    *)
      echo "answer Y(es) or N(o) (y/n or yes/no)"
      ;;
  esac
done

echo "Known devices list:"
echo "${DEVICES_LIST}"

while IFS= read -r DEV; do
  [[ -z "${DEV}" ]] && continue
  [[ "${DEV}" == List* ]] && continue

  SERIAL="$(awk '{print $1}' <<<"${DEV}")"
  STATE="$(awk '{print $2}' <<<"${DEV}")"
  [[ "${STATE}" != "device" ]] && continue

  echo "------------ ${SERIAL}"
  echo "session_stats:"
  pull_dir "${SERIAL}" "session_stats" "${LOG_ROOT}"
  echo "crash_reports/pending:"
  pull_dir "${SERIAL}" "crash_reports/pending" "${CRASH_ROOT}"
  echo "crash_reports/native (stubs):"
  pull_dir "${SERIAL}" "crash_reports/native" "${CRASH_ROOT}"
done <<<"${DEVICES_LIST}"

echo ""
echo "Session stats: ${LOG_ROOT}"
[[ -d "${LOG_ROOT}" ]] && find "${LOG_ROOT}" -type f 2>/dev/null | sort || true
echo ""
echo "Crash reports: ${CRASH_ROOT}"
[[ -d "${CRASH_ROOT}" ]] && find "${CRASH_ROOT}" -type f 2>/dev/null | sort || true
echo ""
echo "run './gradlew :session-studio:run' to analyze session logs"
