#!/system/bin/sh
MODDIR=${0%/*}

# This function is copied from [ Uperf@yc9559 ] module.
wait_until_login() {
    # in case of /data encryption is disabled
    while [ "$(getprop sys.boot_completed)" != "1" ]; do
        sleep 1
    done

    # we doesn't have the permission to rw "/sdcard" before the user unlocks the screen
    local test_file="/sdcard/Android/.PERMISSION_TEST_FREEZE_IT"
    true >"$test_file"
    while [ ! -f "$test_file" ]; do
        true >"$test_file"
        sleep 1
    done
    rm "$test_file"
}

wait_until_login

upTime=$(date "+%Y%m%d %H:%M:%S")

handleCrash(){
    crashTime=$(date "+%Y%m%d %H:%M:%S")

    crashTimeFileName=$(date "+%Y%m%d-%H%M%S")
    crashPath="/sdcard/Android/freezeit_crash${crashTimeFileName}.txt"

    crashContent="[ 开机时间( upTime  ): $upTime ]\n[ 奔溃时间(crashTime): $crashTime ]\n\n"
    crashContent=${crashContent}"交流平台 Our community: Q群:781222669  TelegramGroup: https://t.me/freezeitModule\n\n"
    crashContent=${crashContent}"冻它模块崩溃了，请完整截图以下手机信息或发送当前文件给作者进行问题查找并修复: \n\n酷安 @JARK006 jark006@qq.com\n\n谢谢合作，模块不生效没关系，依旧祝您生活愉快，笑口常开😎\n\n"
    crashContent=${crashContent}"Freezeit module crashed, please take a full and long screenshot of the following mobile phone information or send this file to the author for problem detection and repair: \n\nGithub@JARK006 Email: jark006@qq.com\n\nThanks for your cooperation, it does not matter if the module does not take effect, I still wish you a happy life and keep smiling.😎\n\n"
    echo -e ${crashContent} > $crashPath

    echo -e "\n\n[ 程序输出 Output ]" >> $crashPath
    echo $1 >> $crashPath
    
    echo -e "\n\n[ 产品信息 ProductInfo ]" >> $crashPath
    fgrep "ro.product" /system/build.prop >> $crashPath

    echo -e "\n\n[ 系统构建信息 BuildInfo ]" >> $crashPath
    fgrep "ro.build" /system/build.prop >> $crashPath

    echo -e "\n\n[ CPU架构信息 CPU_Info ]" >> $crashPath
    fgrep "cpu" /system/build.prop >> $crashPath
}

output=`$MODDIR/bin/freezeit 2>/dev/stdout`

if [ $? -ne 0 ]; then
    # 等待一个小可爱😋
    # Waiting for a little cute
    handleCrash $output
fi
