#!/bin/bash
#
# Uninstall this project's OHOS app from all hdc-connected devices.
# bundleName is read from harmonyApp/AppScope/app.json5 (override with -b).
# After uninstall, local harmonyApp/entry build / HAP / intermediates are removed by default.
# Use -c when there is no device: skip uninstall but still clean local artifacts (or hdc missing).
#
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEFAULT_JSON5="$SCRIPT_DIR/harmonyApp/AppScope/app.json5"
APP_JSON5="$DEFAULT_JSON5"
BUNDLE_OVERRIDE=""
DO_CLEAN=0

usage() {
  echo "Usage: $0 [options]"
  echo "  -c        No-device mode: only clean local entry/build, .cxx, libs (still uninstalls if devices exist)"
  echo "  -j PATH   Path to app.json5 (default: harmonyApp/AppScope/app.json5 under script dir)"
  echo "  -b NAME   Override bundle name (skip reading app.json5)"
  echo "  -h        Help"
  exit 0
}

while [[ $# -gt 0 ]]; do
  case $1 in
    -c) DO_CLEAN=1; shift ;;
    -j) APP_JSON5="$2"; shift 2 ;;
    -b) BUNDLE_OVERRIDE="$2"; shift 2 ;;
    -h) usage ;;
    *) echo "Unknown option: $1"; usage ;;
  esac
done

if [[ -n "$BUNDLE_OVERRIDE" ]]; then
  BUNDLE_NAME="$BUNDLE_OVERRIDE"
else
  if [[ ! -f "$APP_JSON5" ]]; then
    echo "Error: app.json5 not found: $APP_JSON5"
    exit 1
  fi
  BUNDLE_NAME=$(grep '"bundleName"' "$APP_JSON5" 2>/dev/null | sed 's/.*"bundleName"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/' | head -1 | tr -d '\r')
  if [[ -z "$BUNDLE_NAME" ]]; then
    echo "Error: could not parse bundleName from $APP_JSON5"
    exit 1
  fi
fi

clean_harmony_entry() {
  local base="$SCRIPT_DIR/harmonyApp/entry"
  if [[ ! -d "$base" ]]; then
    echo "Warning: entry directory not found: $base"
    return 0
  fi
  rm -rf "$base/builds" "$base/build" "$base/.cxx"
  if [[ -d "$base/libs" ]]; then
    find "$base/libs" -type f \( -name '*.so' -o -name '*.SO' \) -delete 2>/dev/null || true
  fi
  rm -rf "$base/libs/arm64-v8a" "$base/libs/x86_64"
  echo "Local clean: entry/build, builds, .cxx, all *.so under libs, libs/arm64-v8a, libs/x86_64"
}

run_uninstall_all() {
  local hdc_bin="$1"
  shift
  local -a ids=("$@")
  echo "Bundle: $BUNDLE_NAME"
  echo "Targets: ${ids[*]}"
  echo "------------------------------------------------------------"
  local tid
  for tid in "${ids[@]}"; do
    echo "[$tid] aa force-stop (ignore errors)"
    "$hdc_bin" -t "$tid" shell aa force-stop "$BUNDLE_NAME" 2>/dev/null || true
    echo "[$tid] bm uninstall -n $BUNDLE_NAME"
    "$hdc_bin" -t "$tid" shell bm uninstall -n "$BUNDLE_NAME" 2>&1 || true
  done
  echo "------------------------------------------------------------"
  echo "Uninstall attempted on ${#ids[@]} device(s) for bundle $BUNDLE_NAME"
}

if [[ $DO_CLEAN -eq 1 ]]; then
  DEVECO_PATH="${DEVECO_PATH:-/Applications/DevEco-Studio.app}"
  DEVECO_HOME="${DEVECO_HOME:-$DEVECO_PATH/Contents}"
  HDC_BIN="$DEVECO_HOME/sdk/default/openharmony/toolchains/hdc"
  DEVICE_IDS=()
  if [[ -d "$DEVECO_PATH" && -x "$HDC_BIN" ]]; then
    while IFS= read -r line; do
      line=$(echo "$line" | tr -d '\r' | xargs)
      [[ -n "$line" ]] && DEVICE_IDS+=("$line")
    done < <("$HDC_BIN" list targets 2>/dev/null | awk '{if (NF>=1) print $1}')
  fi
  if [[ ${#DEVICE_IDS[@]} -gt 0 ]]; then
    echo "Scanning devices (hdc list targets)..."
    run_uninstall_all "$HDC_BIN" "${DEVICE_IDS[@]}"
  else
    if [[ -d "$DEVECO_PATH" && -x "$HDC_BIN" ]]; then
      echo "No connected device; skip uninstall."
    else
      echo "hdc not available; skip uninstall."
    fi
  fi
  echo "Cleaning local harmonyApp/entry artifacts..."
  clean_harmony_entry
  echo "Done."
  exit 0
fi

DEVECO_PATH="${DEVECO_PATH:-/Applications/DevEco-Studio.app}"
if [[ ! -d "$DEVECO_PATH" ]]; then
  echo "Error: DevEco Studio not found at $DEVECO_PATH. Set DEVECO_PATH."
  exit 1
fi

DEVECO_HOME="${DEVECO_HOME:-$DEVECO_PATH/Contents}"
HDC_BIN="$DEVECO_HOME/sdk/default/openharmony/toolchains/hdc"

if [[ ! -x "$HDC_BIN" ]]; then
  echo "Error: hdc not found at $HDC_BIN"
  exit 1
fi

echo "Scanning devices (hdc list targets)..."

DEVICE_IDS=()
while IFS= read -r line; do
  line=$(echo "$line" | tr -d '\r' | xargs)
  [[ -n "$line" ]] && DEVICE_IDS+=("$line")
done < <("$HDC_BIN" list targets 2>/dev/null | awk '{if (NF>=1) print $1}')

if [[ ${#DEVICE_IDS[@]} -eq 0 ]]; then
  echo "Error: no device found. Connect device and run: hdc list targets"
  exit 1
fi

run_uninstall_all "$HDC_BIN" "${DEVICE_IDS[@]}"
echo "Cleaning local harmonyApp/entry artifacts..."
clean_harmony_entry
echo "Done."
