#!/system/bin/sh

MODDIR=${0%/*}
# shellcheck disable=SC1090
. "$MODDIR/common.sh"

MAX_KB=2048
LOGCAT_LINES=2500
BUNDLE_DIR=""

while [ $# -gt 0 ]; do
    case "$1" in
        --max-kb)
            shift
            MAX_KB="${1:-2048}"
            ;;
        --logcat-lines)
            shift
            LOGCAT_LINES="${1:-2500}"
            ;;
        --bundle-dir)
            shift
            BUNDLE_DIR="${1:-}"
            ;;
    esac
    shift
done

case "$MAX_KB" in
    ''|*[!0-9]*) MAX_KB=2048 ;;
esac
case "$LOGCAT_LINES" in
    ''|*[!0-9]*) LOGCAT_LINES=2500 ;;
esac
[ "$MAX_KB" -lt 128 ] 2>/dev/null && MAX_KB=128
[ "$MAX_KB" -gt 8192 ] 2>/dev/null && MAX_KB=8192
[ "$LOGCAT_LINES" -lt 100 ] 2>/dev/null && LOGCAT_LINES=100
[ "$LOGCAT_LINES" -gt 20000 ] 2>/dev/null && LOGCAT_LINES=20000

MAX_BYTES=$((MAX_KB * 1024))

section() {
    printf '\n========== %s ==========' "$1"
    printf '\n'
}

safe_archive_rel() {
    printf '%s' "files/${1#/}" | sed 's#[^A-Za-z0-9._/-]#_#g'
}

copy_original_file() {
    file="$1"
    [ -n "$file" ] || return 0
    [ -f "$file" ] || return 0
    [ -r "$file" ] || return 0

    rel="$(safe_archive_rel "$file")"
    dest="$BUNDLE_DIR/$rel"
    mkdir -p "${dest%/*}" 2>/dev/null || return 0
    if cp -p "$file" "$dest" 2>/dev/null; then
        :
    else
        cat "$file" >"$dest" 2>/dev/null || return 0
    fi
    size="$(wc -c <"$file" 2>/dev/null | tr -d ' ')"
    printf '%s\t%s\t%s\n' "$file" "$rel" "${size:-0}" >>"$BUNDLE_DIR/metadata/original-files.tsv"
}

safe_file_tail() {
    file="$1"
    label="$2"
    section "$label"
    printf 'path=%s\n' "$file"
    if [ ! -e "$file" ]; then
        printf '(missing)\n'
        return 0
    fi
    if [ ! -r "$file" ]; then
        printf '(not readable)\n'
        return 0
    fi
    size="$(wc -c <"$file" 2>/dev/null | tr -d ' ')"
    printf 'size=%s maxBytes=%s\n' "${size:-unknown}" "$MAX_BYTES"
    if [ "${size:-0}" -gt "$MAX_BYTES" ] 2>/dev/null; then
        printf '%s\n' "--- truncated: last $MAX_BYTES bytes ---"
        tail -c "$MAX_BYTES" "$file" 2>/dev/null | tr -d '\000'
    else
        cat "$file" 2>/dev/null | tr -d '\000'
    fi
    printf '\n'
}

append_command() {
    title="$1"
    shift
    section "$title"
    "$@" 2>&1 | tr -d '\000'
    printf '\n'
}

append_logcat() {
    if command -v logcat >/dev/null 2>&1; then
        logcat -d -v threadtime -t "$LOGCAT_LINES" \
            -s CloudPhoneDaemon cloudphone-magisk CloudPhoneManager CloudPhoneManagerHelper \
               AnXinChong AnXinChongApi AnXinChongStore LSPosed-Bridge \
               CloudphoneDisplayHelper CloudphoneDisplayHelperNative 2>&1 | tr -d '\000'
    else
        printf 'logcat binary not found\n'
    fi
}

append_file_group() {
    title="$1"
    shift
    section "$title"
    found=0
    for file in "$@"; do
        [ -n "$file" ] || continue
        [ -e "$file" ] || continue
        found=1
        printf '%s\n' "$file"
    done
    [ "$found" = 0 ] && printf '(empty)\n'
    printf '\n'
    for file in "$@"; do
        [ -n "$file" ] || continue
        [ -e "$file" ] || continue
        safe_file_tail "$file" "file: $file"
    done
}

load_config

now="$(date '+%Y-%m-%d %H:%M:%S %z' 2>/dev/null || echo unknown-time)"
serial="$(getprop_value ro.serialno)"
model="$(getprop_value ro.product.model)"
brand="$(getprop_value ro.product.brand)"
android_ver="$(getprop_value ro.build.version.release)"
sdk_int="$(getprop_value ro.build.version.sdk)"
device_id="$(resolve_device_id)"

DAEMON_LOG_FILES="$(
    {
        find "$RUNTIME_LOG_DIR" -maxdepth 1 -type f \( -name 'cloudphone*.log' -o -name 'cloudphone_*.log' \) 2>/dev/null
        find "$RUNTIME_DIR" -maxdepth 1 -type f \( -name 'cloudphone*.log' -o -name 'cloudphone_*.log' \) 2>/dev/null
    } | sort -u | tail -n 8
)"
ANXINCHONG_LOG_FILES="$(
    {
        find "$RUNTIME_LOG_DIR/anxinchong" -maxdepth 1 -type f -name 'anxinchong*.log' 2>/dev/null
        find "$RUNTIME_LOG_DIR" -maxdepth 1 -type f -name 'anxinchong*.log' 2>/dev/null
        find /data/user -type f -path '*/files/anxinchong_logs/*.log' 2>/dev/null
    } | sort -u | tail -n 16
)"
DISPLAY_HELPER_LOG_FILES="$(
    {
        find "$RUNTIME_LOG_DIR" -maxdepth 1 -type f \( -name '*display-helper*.log' -o -name '*display_mirror*.log' \) 2>/dev/null
        find "$DISPLAY_HELPER_RUNTIME_DIR" -maxdepth 1 -type f \( -name '*display-helper*.log' -o -name '*display_mirror*.log' \) 2>/dev/null
    } | sort -u | tail -n 12
)"

if [ -n "$BUNDLE_DIR" ]; then
    rm -rf "$BUNDLE_DIR" 2>/dev/null || true
    mkdir -p "$BUNDLE_DIR/metadata" "$BUNDLE_DIR/generated" 2>/dev/null || exit 2
    : >"$BUNDLE_DIR/metadata/original-files.tsv"

    cat >"$BUNDLE_DIR/metadata/export-meta.txt" <<META
createdAt=$now
moduleDir=$MODDIR
runtimeDir=$RUNTIME_DIR
socket=$SOCK_FILE
deviceId=$device_id
serial=$serial
brand=$brand
model=$model
android=$android_ver
sdk=$sdk_int
maxKb=$MAX_KB
logcatLines=$LOGCAT_LINES
adb=not-used
META

    sh "$MODDIR/info.sh" >"$BUNDLE_DIR/generated/module-info.json" 2>&1
    ps -A 2>/dev/null | grep -E "cloudphone|manager_helper|anxinchong|browndust|google.android.gms" >"$BUNDLE_DIR/generated/process-snapshot.txt" 2>&1 || true
    append_logcat >"$BUNDLE_DIR/generated/logcat-threadtime.txt" 2>&1

    set -- $DAEMON_LOG_FILES
    for file in "$@"; do copy_original_file "$file"; done
    copy_original_file "$SERVICE_LOG_FILE"
    copy_original_file "$RUNTIME_DIR/manager-helper.log"
    copy_original_file "$RUNTIME_DIR/webui-action.log"
    set -- $DISPLAY_HELPER_LOG_FILES
    for file in "$@"; do copy_original_file "$file"; done
    set -- $ANXINCHONG_LOG_FILES
    for file in "$@"; do copy_original_file "$file"; done

    printf 'generatedAt=%s\n' "$now"
    printf 'moduleDir=%s\n' "$MODDIR"
    printf 'runtimeDir=%s\n' "$RUNTIME_DIR"
    printf 'bundleDir=%s\n' "$BUNDLE_DIR"
    printf 'deviceId=%s\n' "$device_id"
    printf 'fileCount=%s\n' "$(find "$BUNDLE_DIR" -type f 2>/dev/null | wc -l | tr -d ' ')"
    exit 0
fi

section "CloudPhone log export"
printf 'generatedAt=%s\n' "$now"
printf 'moduleDir=%s\n' "$MODDIR"
printf 'runtimeDir=%s\n' "$RUNTIME_DIR"
printf 'socket=%s\n' "$SOCK_FILE"
printf 'deviceId=%s\n' "$device_id"
printf 'serial=%s\n' "$serial"
printf 'brand=%s\n' "$brand"
printf 'model=%s\n' "$model"
printf 'android=%s sdk=%s\n' "$android_ver" "$sdk_int"
printf 'maxKb=%s logcatLines=%s\n' "$MAX_KB" "$LOGCAT_LINES"
printf 'note=this bundle is collected on-device by root helper/module scripts; adb is not used.\n'

append_command "module info" sh "$MODDIR/info.sh"
append_command "process snapshot" sh -c 'ps -A 2>/dev/null | grep -E "cloudphone|manager_helper|anxinchong|browndust|google.android.gms" || true'

set -- $DAEMON_LOG_FILES
append_file_group "daemon log files" "$@"
safe_file_tail "$SERVICE_LOG_FILE" "service log"
safe_file_tail "$RUNTIME_DIR/manager-helper.log" "manager helper log"
safe_file_tail "$RUNTIME_DIR/webui-action.log" "webui action log"
set -- $DISPLAY_HELPER_LOG_FILES
append_file_group "display helper log files" "$@"

set -- $ANXINCHONG_LOG_FILES
append_file_group "AnXinChong file logs" "$@"

section "Android logcat snapshot (direct logcat, no adb)"
append_logcat
printf '\n'
