#!/bin/sh
Lianprint(){
    echo "$@"
    sleep 0.04
}
get_choose(){
    local c
    while :; do
        c=$(getevent -qlc 1 | awk '{print $3}')
        case "$c" in
            KEY_VOLUMEUP)   Lianprint 1; break ;;
            KEY_VOLUMEDOWN) Lianprint 0; break ;;
            *) continue ;;
        esac
    done
}
validate_core_files() {
  ui_print "=== 开始校验核心文件完整性 ==="
  unzip -o "$ZIPFILE" 'verify.sh' -d "$TMPDIR" >&2
  if [ ! -f "$TMPDIR/verify.sh" ]; then
    ui_print "! 无法提取verify.sh，压缩包可能损坏"
    abort
  fi
  chmod +x "$TMPDIR/verify.sh"
  local core_files="action.sh customize.sh keybox.xml module.prop post-fs-data.sh service.sh uninstall.sh verify.sh"
  for file in $core_files; do
    ui_print "- 正在校验 $file..."
    "$TMPDIR/verify.sh" "$ZIPFILE" "$file" "$MODPATH"
    if [ $? -ne 0 ]; then
      ui_print "! $file 校验失败，请重新下载压缩包"
      abort
    fi
  done
  ui_print "=== 所有核心文件校验通过 ==="
}
Lianprint "欢迎使用 ☞全管理器隐藏模块☜"
VERSION=$(grep_prop version "${TMPDIR}/module.prop")
Lianprint "当前版本:『正式版』${VERSION}"
Lianprint "————————————"
Lianprint "使用须知:"
Lianprint "请确保您当前设备处理器为"
Lianprint "64位处理器，且安卓版本为"
Lianprint "安卓10及以上且您有一定的"
Lianprint "动手能力。"
Lianprint "————————————"
Lianprint "咱们先暂停5秒，你慢慢看"
sleep 5
Lianprint "为了保证您的合法权益，请先阅读用户协议"
Lianprint "即将弹出用户协议，请仔细阅读"
Lianprint "全管理器隐藏模块（${VERSION} 正式版）用户协议"
Lianprint "1. 本协议是您与模块作者“璃安”就使用本模块订立的协议，"
Lianprint "   您使用本模块即视为接受本协议。"
Lianprint "2. 作者授予您个人非商业免费使用权，"
Lianprint "   禁止反向工程、破解、商业使用或传播未经授权版本。"
Lianprint "3. 本版本为正式版，可能存在功能不稳定、设备异常风险，"
Lianprint "   作者不承诺稳定性，使用前请备份数据。"
Lianprint "4. 因使用本模块导致的设备损坏、数据丢失，"
Lianprint "   或第三方软件（如李跳跳）相关风险，作者不承担责任。"
Lianprint "5. 本模块知识产权归作者所有，未经许可不得侵犯。"
Lianprint "6. 您违反协议时作者可终止您的使用权限，"
Lianprint "   您卸载模块即终止协议（知识产权、责任限制条款除外）。"
Lianprint "7. 本模块并不适用于全部设备，"
Lianprint "   如果您刷入本模块后隐藏失败与本模块无关。"
Lianprint "8. 本模块若推出正式版则代表已经过兼容性及安全性测试，"
Lianprint "9. 本模块为整合模块包，所有隐藏效果依赖于所附带的模块，本身不含有隐藏效果。"
Lianprint "10. 本模块内置刷入逻辑全公开透明，不含任何格机/锁机程序，如您介意请勿使用！"
Lianprint "11.如您无法刷入，与本模块无关。"
Lianprint "您是否已经阅读并同意使用本模块?"
Lianprint "同意之前请先确保已经完成了本协议的阅读"
Lianprint "本模块预计安装时间3-5分钟"
Lianprint "音量上键 = 同意并安装 | 音量下键 = 拒绝并取消安装"
if [ "$(get_choose)" = "1" ]; then
    Lianprint "模块将执行后续操作" 
else
    Lianprint "已选择：取消安装"
    Lianprint "! 若需使用模块，请重新执行脚本并同意用户协议"
    exit 1
fi
Lianprint "正在检测Root环境...请稍后"
ManagerType=""
ManagerNumber=0
Magiskpath="magisk"
KSUpath="ksu"
APatchpath="apatch"

if command -v "$Magiskpath" >/dev/null 2>&1; then
    ManagerType="Magisk"
    ManagerNumber=$((ManagerNumber + 1))
    Lianprint "发现Magisk环境"
fi
if [ -d "/data/adb/ksu" ] || command -v "$KSUpath" >/dev/null 2>&1; then
    ManagerType="KernelSU"
    ManagerNumber=$((ManagerNumber + 1))
    Lianprint "发现KernelSU环境"
fi
if [ -d "/data/adb/apatch" ] || [ -d "/data/adb/ap" ]; then
    ManagerType="APatch"
    ManagerNumber=$((ManagerNumber + 1))
    Lianprint "发现APatch环境"
fi


if [ "$ManagerNumber" -gt 1 ]; then
    Lianprint "⚠️ 环境异常：检测到 $ManagerNumber 个 Root 管理器共存！"
    Lianprint "🚫 禁止安装，请刷机后保留单一 Root 环境再尝试！"
    exit 1
fi

if [ "$ManagerNumber" -eq 0 ]; then
    Lianprint "🚫 未检测到支持的 Root 管理器！"
    exit 1
fi
case "$ManagerType" in
    Magisk)
        manager_path="$Magiskpath"
        module_suffix="mgk" 
        ;;
    KernelSU)
        manager_path="$KSUpath"
        module_suffix="su" 
        ;;
    APatch)
        manager_path="$APatchpath"
        module_suffix="apa" 
        ;;
esac
Lianprint "正在验证 $manager_path 版本设置"
validate_core_files
sleep 5
API_LEVEL=$(getprop ro.build.version.sdk)
if [ "$API_LEVEL" -ge 29 ]; then
  ABI="$(getprop ro.product.cpu.abi)"
  Lianprint "$manager_path 版本信息验证通过"
  Lianprint "当前设备API版本：$API_LEVEL（符合要求），CPU架构：$ABI"
else
  Lianprint "错误：当前设备安卓API版本为 $API_LEVEL，需≥29才能运行（安卓9以上）"
  exit 1
fi
Lianprint "======================================"
Lianprint "请选择需要刷入的内容（逐项确认）"
Lianprint "======================================"
install_detect_apk=0
Lianprint "是否安装【检测软件】（推荐)？"
Lianprint "使用完毕后请及时删除"
Lianprint "音量上键 = 安装 | 音量下键 = 跳过"
[ "$(get_choose)" = "1" ] && install_detect_apk=1 && Lianprint "已选择：安装检测软件" || Lianprint "已选择：跳过检测软件安装"
install_tiaotiao_apk=0
install_tiaotiao_rule=0
Lianprint "是否安装【李跳跳(跳过弹窗广告)】？"
Lianprint "音量上键 = 安装 | 音量下键 = 跳过"
if [ "$(get_choose)" = "1" ]; then
    install_tiaotiao_apk=1
    install_tiaotiao_rule=1
    Lianprint "已选择：安装李跳跳APK + 规则文件" 
else
    Lianprint "已选择：跳过李跳跳安装"
fi
sleep 2
RULES_SRC="$MODPATH/data/apk2/Tiao.txt"
RULES_DST="/storage/emulated/0/李跳跳最新规则.txt"
Lianprint "======================================"
Lianprint "开始执行应用模块刷入操作（当前管理器：$ManagerType）"
Lianprint "======================================"
sleep 2
Lianprint "正在调整应用安装权限为宽容模式..."
settings put global install_non_market_apps 1 >&2
[ $? -eq 0 ] && Lianprint "安装权限调整成功" || Lianprint "警告：安装权限调整失败"
sleep 2
if [ $install_detect_apk -eq 1 ]; then
    Lianprint "正在安装检测软件..."
    for apk in "$MODPATH"/data/apk1/*.apk; do
        [ -f "$apk" ] && pm install -r "$apk" && Lianprint "成功安装：$(basename "$apk")" || Lianprint "警告：$(basename "$apk") 安装失败"
    done
    Lianprint "检测软件安装流程结束"
fi
sleep 2
Lianprint "预计于5秒后开始下一阶段"
Lianprint "正在安装隐藏必需插件，请稍后..."
for apk in "$MODPATH"/data/apk3/*.apk; do
    [ -f "$apk" ] && pm install -r "$apk" && Lianprint "成功安装：$(basename "$apk")" || Lianprint "警告：$(basename "$apk") 安装失败"
done
Lianprint "应用隐藏列表安装流程结束"
sleep 2
Lianprint "预计于5秒后开始下一阶段"
if [ $install_tiaotiao_apk -eq 1 ]; then
    Lianprint "正在安装李跳跳APK..."
    for apk in "$MODPATH"/data/apk2/*.apk; do
        if [ -f "$apk" ]; then
            pm install -r "$apk" && {
                Lianprint "成功安装：$(basename "$apk")"
                if [ $install_tiaotiao_rule -eq 1 ] && [ -f "$RULES_SRC" ]; then
    cp -f "$RULES_SRC" "$RULES_DST" && Lianprint "李跳跳规则复制成功" || Lianprint "警告：李跳跳规则复制失败"
                fi
            } || Lianprint "警告：$(basename "$apk") 安装失败"
        fi
    done
    Lianprint "李跳跳安装流程结束"
fi
sleep 2

Lianprint "正在安装 $manager_path 模块..."

Lianprint "【1/2】开始安装通用模块"
for ZIPFILE in /data/adb/modules_update/FullManagerHideModule/data/module/*.all; do
    if [ -f "$ZIPFILE" ]; then
        local MOD_NAME=$(basename "$ZIPFILE")
        Lianprint "正在安装通用模块: $MOD_NAME"
        install_module
        if [ $? -eq 0 ]; then
            Lianprint "通用模块 $MOD_NAME 安装成功，清理安装包..."
            rm -rf "$ZIPFILE"
            sleep 2
        else
            Lianprint "警告: 通用模块 $MOD_NAME 安装失败！"
        fi
    fi
done

Lianprint "【2/2】开始安装 $manager_path 专属模块"
for ZIPFILE in /data/adb/modules_update/FullManagerHideModule/data/module/"$module_suffix"/*."$module_suffix"; do
    if [ -f "$ZIPFILE" ]; then
        local MOD_NAME=$(basename "$ZIPFILE")
        Lianprint "正在安装专属模块: $MOD_NAME"
        install_module
        if [ $? -eq 0 ]; then
            Lianprint "专属模块 $MOD_NAME 安装成功，清理安装包..."
            rm -rf "$ZIPFILE"
            sleep 2
        else
            Lianprint "警告: 专属模块 $MOD_NAME 安装失败！"
        fi
    fi
done

Lianprint "隐藏模块已经完成安装任务，正在进行最后的配置，请稍后……"
Lianprint "即将开始执行配置操作"
if [ -d /data/adb/modules/tricky_store ]; then
  mkdir -p /data/adb/tricky_store
  mv "$MODPATH/keybox.xml" /data/adb/tricky_store
  cp -r "$MODPATH/keybox.xml" /data/adb/
  mv /data/adb/keybox.xml /data/adb/tricky_store
  touch "$MODPATH/TrickyStoreListDTGX_Task"
else
  [ ! -d /data/adb/modules/FrameworkPatcherGo ] && {
    Lianprint "提示：未安装TrickyStore，密钥装填将在其安装后执行"
    touch "$MODPATH/TrickyStoreKeyBox_Task"
  }
fi
 Lianprint "提示：TrickyStore密钥装填完成，已启用动态更新模式，请手动使用trickystore进行有效秘钥配置"
 Lianprint "已完成25%"
Lianprint "提示：初始化自动哈希解决功能"
if pm list packages | grep -q "com.reveny.vbmetafix.service"; then
  Lianprint "操作：卸载旧版哈希服务应用"
  UninstallOutput=$(pm uninstall com.reveny.vbmetafix.service)
  Lianprint "卸载结果：$UninstallOutput"
fi
Lianprint "已完成50%"
if [ -f "$MODPATH/HashService/GetHashServiceApp.apk" ]; then
  Lianprint "操作：安装哈希服务应用"
  InstallOutput=$(pm install "$MODPATH/HashService/GetHashServiceApp.apk")
  Lianprint "安装结果：$InstallOutput"
  pm list packages | grep -q "com.reveny.vbmetafix.service" || Lianprint "错误：哈希服务应用安装失败"
else
  Lianprint "错误：哈希服务应用文件缺失"
fi
Lianprint "已完成75%"
CONFIG_FILE="/data/data/com.tsng.hidemyapplist/files/config.json"
NEW_CONFIG="/data/adb/modules_update/FullManagerHideModule/data/config.json"
cp -f "$NEW_CONFIG" "$CONFIG_FILE"
 Lianprint "$NEW_CONFIG" > "$CONFIG_FILE"
Lianprint "应用隐藏列表配置已导入"
Lianprint "完成度100%"
Lianprint "======================================"
Lianprint "请用音量键选择："
Lianprint "音量上键 = 跳转哔哩哔哩观看教程"
Lianprint "音量下键 = 跳过"
Lianprint "======================================"
if [ "$(get_choose)" = "1" ]; then
    Lianprint "正在启动浏览器..."
    Lianprint "别忘了给up点赞三连！"
    am start -a android.intent.action.VIEW -d "https://b23.tv/3YEDCj7" 
else
    Lianprint "哼！不看拉倒，不会配置别来找我～罚等5秒"
    sleep 5
fi
Lianprint "======================================"
Lianprint "请用音量键选择："
Lianprint "音量上键 = 跳转技术交流群"
Lianprint "音量下键 = 跳过"
Lianprint "等待按键中..."
if [ "$(get_choose)" = "1" ]; then
     Lianprint "3秒后跳转QQ..."
     am start -a android.intent.action.VIEW -d "https://qm.qq.com/q/cPRpJ9NLbi"
else
     Lianprint "嗷呜～不加群祝你黑砖！快点点关注感谢一下～"
fi
Lianprint "正在恢复应用安装权限为默认模式..."
settings put global install_non_market_apps 0 >&2
[ $? -eq 0 ] && Lianprint "安装权限恢复成功" || Lianprint "警告：安装权限恢复失败，请手动检查"
Lianprint "所有流程结束，祝你玩机“愉快”！"
exit 0
