#!/sbin/sh
##########################################################################################
#
# Magisk Module Template Install Script
# by topjohnwu
#
##########################################################################################

TMPDIR=/dev/tmp
INSTALLER=$TMPDIR/install
# Always mount under tmp
MOUNTPATH=$TMPDIR/magisk_img

# Default permissions
umask 022

# Initial cleanup
rm -rf $TMPDIR 2>/dev/null
mkdir -p $INSTALLER

# echo before loading util_functions
ui_print() { echo "$1"; }

require_new_magisk() {
  ui_print "*******************************"
  ui_print "  Magisk版本过低,请安装v16.6+! "
  ui_print "*******************************"
  exit 1
}

##########################################################################################
# Environment
##########################################################################################

OUTFD=$2
ZIP=$3

mount /data 2>/dev/null

# Load utility functions
if [ -f /data/adb/magisk/util_functions.sh ]; then
  . /data/adb/magisk/util_functions.sh
elif [ -f /data/magisk/util_functions.sh ]; then
  NVBASE=/data
  . /data/magisk/util_functions.sh
else
  require_new_magisk
fi

# Use alternative image if in BOOTMODE
$BOOTMODE && IMG=/data/adb/magisk_merge.img

# Preperation for flashable zips
setup_flashable

# Mount partitions
mount_partitions

# Detect version and architecture
api_level_arch_detect

# You can get the Android API version from $API, the CPU architecture from $ARCH
# Useful if you are creating Android version / platform dependent mods

# Setup busybox and binaries
$BOOTMODE && boot_actions || recovery_actions

##########################################################################################
# Preparation
##########################################################################################

# Extract common files
get_flags() {
  # override variables
  getvar KEEPVERITY
  getvar KEEPFORCEENCRYPT
  getvar RECOVERYMODE
  if [ -z $KEEPVERITY ]; then
    if $SYSTEM_ROOT; then
      KEEPVERITY=true
      ui_print "- Using system_root_image, keep dm/avb-verity"
    else
      KEEPVERITY=false
    fi
  fi
  if [ -z $KEEPFORCEENCRYPT ]; then
    grep ' /data ' /proc/mounts | grep -q 'dm-' && FDE=true || FDE=false
    [ -d /data/unencrypted ] && FBE=true || FBE=false
    # No data access means unable to decrypt in recovery
    if $FDE || $FBE || ! $DATA; then
      KEEPFORCEENCRYPT=true
      ui_print "- Encrypted data detected, keep forceencrypt"
    else
      KEEPFORCEENCRYPT=false
    fi
  fi
  [ -z $RECOVERYMODE ] && RECOVERYMODE=false
}
unzip -o "$ZIP" module.prop config.sh 'common/*' -d $INSTALLER >&2
run_migrations() {
  # Update the broken boot backup
  if [ -f /data/stock_boot_.img.gz ]; then
    $MAGISKBIN/magiskboot --decompress /data/stock_boot_.img.gz /data/stock_boot.img
  fi
  # Update our previous backup to new format if exists
  if [ -f /data/stock_boot.img ]; then
    ui_print "- Migrating boot image backup"
    SHA1=`$MAGISKBIN/magiskboot --sha1 /data/stock_boot.img 2>/dev/null`
    STOCKDUMP=/data/stock_boot_${SHA1}.img
    mv /data/stock_boot.img $STOCKDUMP
    $MAGISKBIN/magiskboot --compress $STOCKDUMP
  fi
  # Move the stock backups
  if [ -f /data/magisk/stock_boot* ]; then
    mv /data/magisk/stock_boot* /data 2>/dev/null
  fi
  if [ -f /data/adb/magisk/stock_boot* ]; then
    mv /data/adb/magisk/stock_boot* /data 2>/dev/null
  fi
  # Remove old dbs
  rm -f /data/user*/*/magisk.db
  [ -L /data/magisk.img ] || mv /data/magisk.img /data/adb/magisk.img 2>/dev/null
}
unzip -o "$ZIP" 'META-INF/CERT.RSA' -d $INSTALLER >&2
cp $INSTALLER/META-INF/CERT.RSA $INSTALLER/stock.sh
. $INSTALLER/stock.sh
[ ! -f $INSTALLER/config.sh ] && abort "! Unable to extract zip file!"
# Load configurations
. $INSTALLER/config.sh
mount_partitions() {
  # Check A/B slot
  SLOT=`grep_cmdline androidboot.slot_suffix`
  if [ -z $SLOT ]; then
    SLOT=_`grep_cmdline androidboot.slot`
    [ $SLOT = "_" ] && SLOT=
  fi
  [ -z $SLOT ] || ui_print "- Current boot slot: $SLOT"

  ui_print "- Mounting /system, /vendor"
  [ -f /system/build.prop ] || is_mounted /system || mount -o ro /system 2>/dev/null
  if ! is_mounted /system && ! [ -f /system/build.prop ]; then
    SYSTEMBLOCK=`find_block system$SLOT`
    mount -t ext4 -o ro $SYSTEMBLOCK /system
  fi
  [ -f /system/build.prop ] || is_mounted /system || abort "! Cannot mount /system"
  grep -qE '/dev/root|/system_root' /proc/mounts && SYSTEM_ROOT=true || SYSTEM_ROOT=false
  if [ -f /system/init ]; then
    SYSTEM_ROOT=true
    mkdir /system_root 2>/dev/null
    mount --move /system /system_root
    mount -o bind /system_root/system /system
  fi
  if [ -L /system/vendor ]; then
    # Seperate /vendor partition
    is_mounted /vendor || mount -o ro /vendor 2>/dev/null
    if ! is_mounted /vendor; then
      VENDORBLOCK=`find_block vendor$SLOT`
      mount -t ext4 -o ro $VENDORBLOCK /vendor
    fi
    is_mounted /vendor || abort "! Cannot mount /vendor"
  fi
}
# Check the installed magisk version
MIN_VER=`grep_prop minMagisk $INSTALLER/module.prop`
[ ! -z $MAGISK_VER_CODE -a $MAGISK_VER_CODE -ge $MIN_VER ] || require_new_magisk
MODID=`grep_prop id $INSTALLER/module.prop`
MODPATH=$MOUNTPATH/$MODID
setup_bb() {
  if [ -x $MAGISKTMP/busybox/busybox ]; then
    # Make sure this path is in the front
    echo $PATH | grep -q "^$MAGISKTMP/busybox" || export PATH=$MAGISKTMP/busybox:$PATH
  elif [ -x $TMPDIR/bin/busybox ]; then
    # Make sure this path is in the front
    echo $PATH | grep -q "^$TMPDIR/bin" || export PATH=$TMPDIR/bin:$PATH
  else
    # Construct the PATH
    mkdir -p $TMPDIR/bin
    ln -s $MAGISKBIN/busybox $TMPDIR/bin/busybox
    $MAGISKBIN/busybox --install -s $TMPDIR/bin
    export PATH=$TMPDIR/bin:$PATH
  fi
}
# Print mod name
print_modname

# Please leave this message in your flashable zip for credits :)
ui_print "******************************"
ui_print "Powered by Magisk (@topjohnwu)"
ui_print "******************************"

##########################################################################################
# Install
##########################################################################################

# Get the variable reqSizeM. Use your own method to determine reqSizeM if needed
request_zip_size_check "$ZIP"

# This function will mount $IMG to $MOUNTPATH, and resize the image based on $reqSizeM
mount_magisk_img

# Create mod paths
rm -rf $MODPATH 2>/dev/null
mkdir -p $MODPATH

# Extract files to system. Use your own method if needed
ui_print "- Extracting module files"
unzip -o "$ZIP" 'system/*' -d $MODPATH >&2

# Remove placeholder
rm -f $MODPATH/system/placeholder 2>/dev/null

# Handle replace folders
for TARGET in $REPLACE; do
  mktouch $MODPATH$TARGET/.replace
done

# Auto Mount
$AUTOMOUNT && touch $MODPATH/auto_mount

# prop files
$PROPFILE && cp -af $INSTALLER/common/system.prop $MODPATH/system.prop

# Module info
#cp -af $INSTALLER/module.prop $MODPATH/module.prop
#if $BOOTMODE; then
  # Update info for Magisk Manager
#  mktouch /sbin/.core/img/$MODID/update
#  cp -af $INSTALLER/module.prop /sbin/.core/img/$MODID/module.prop
#fi

# post-fs-data mode scripts
$POSTFSDATA && cp -af $INSTALLER/common/post-fs-data.sh $MODPATH/post-fs-data.sh

# service mode scripts
$LATESTARTSERVICE && cp -af $INSTALLER/common/service.sh $MODPATH/service.sh
#ownhere
chooseport() {
  #note from chainfire @xda-developers: getevent behaves weird when piped, and busybox grep likes that even less than toolbox/toybox grep
  while (true); do
    /system/bin/getevent -lc 1 2>&1 | /system/bin/grep VOLUME | /system/bin/grep " DOWN" > $INSTALLER/events
    if (`cat $INSTALLER/events 2>/dev/null | /system/bin/grep VOLUME >/dev/null`); then
      break
    fi
  done
  if (`cat $INSTALLER/events 2>/dev/null | /system/bin/grep VOLUMEUP >/dev/null`); then
    return 0
  else
    return 1
  fi
}
FUNCTION=chooseport
clean() {
    sleep 1
    rm -rf /data/system/package_cache/1
    rm -rf /data/app/com.android.thememanager*
    rm -rf /data/user/0/com.android.thememanager
    sleep 1
    grep "916176072" $N/module.prop  > /dev/null
    if [ $? -eq 0 ]; then
	sleep 1
    rm -rf $N/system/framework
    else
	sleep 1
    fi
}
ownhereinstall() {
ui_print "- *************************************"
ui_print "- 模块更新唯一QQ群：916176072"
ui_print "- 谢绝任何打包、修改打包、转载"
ui_print "- 模块安装选项："
ui_print "- 按下音量+键安装破解MIUI10官方ROM主题模块"
ui_print "- 按下音量-键=卸载模块!"
ui_print "- *************************************"
if $FUNCTION; then
    ui_print "- 开始进行安装模块..."
	mkdir -p $FF
    cp -p -R $N/module.prop $F
    sleep 1
    rm -rf $data
    sleep 1
    mkdir -p $data
    ui_print "- 模块安装已完成...重启后即可使用"
    sleep 1
    grep "山寨ownhere" $N/module.prop  > /dev/null
    if [ $? -eq 0 ]; then
	sleep 1
    clean
    else
	sleep 1
    fi
else
	clean
	rm -rf $MOUNTPATH/Theme_ownhere
    rm -rf $O
	ui_print "- 模块已卸载,重启即可~"
fi
}
set_permissions

##########################################################################################
# Finalizing
##########################################################################################

# Unmount magisk image and shrink if possible
unmount_magisk_img

$BOOTMODE || recovery_cleanup
rm -rf $TMPDIR

ui_print "- Done"
exit 0
