#!/sbin/sh
#
# afzc script to perform various operations created by Nikhil Menghani
#
# inspired from topjohnwu's (@xda) magisk
# inspired from xXx's (@xda) no limits module
# inspired from osm0sis's (@xda) universal shell script functions
# inspired from opengapps installer script (reference below)
# https://github.com/opengapps/opengapps/blob/master/scripts/inc.installer.sh
#

#Setting up variables
OFD=$1
ZIPFILE="$2"
ZIPDIR=$(dirname "$ZIPFILE")
OUTFD=/proc/self/fd/$OFD
system="/system"
product=""
addonDir="/tmp/addon"
nikGappsLog="/tmp/NikGapps.log"
datetime=$(date +%Y_%m_%d_%H_%M_%S)
nikGappsLogFile="NikGapps_logs_$datetime.tar.gz"
recoveryLog=/tmp/recovery.log
logDir="/tmp/NikGapps/logs"
nikGappsDir="/sdcard/NikGapps"

find_config() {
  if [ -f "$ZIPDIR/nikgapps.config" ]; then
    nikgapps_config_file_name="$ZIPDIR/nikgapps.config"
  else
    nikgapps_config_file_name="$nikGappsDir/nikgapps.config"
  fi

  if [ -f "$ZIPDIR/debloater.config" ]; then
    debloater_config_file_name="$ZIPDIR/debloater.config"
  else
    debloater_config_file_name="/sdcard/NikGapps/debloater.config"
  fi
}

check_if_system_mounted_rw() {
  rm -rf "$system/nikgapps.config"
  cp -f "$nikgapps_config_file_name" "$system/nikgapps.config"
  if [ -f "$system/nikgapps.config" ]; then
    addToLog "- System ($system) is properly mounted as rw"
  else
    abort "System is not mounted as rw, Installation failed!"
  fi
}

[ -z "$TMPDIR" ] && TMPDIR=/dev/tmp

test "$ANDROID_ROOT" || ANDROID_ROOT=/system

# show_progress <amount> <time>
show_progress() { echo "progress $1 $2" >>"$OUTFD"; }
# set_progress <amount>
set_progress() { echo "set_progress $1" >>"$OUTFD"; }

makeDir() {
  mkdir -p "$nikGappsDir"
  mkdir -p "$addonDir"
  mkdir -p "$logDir"
}

cleanup() {
  #rm files
  rm -rf "/sdcard/NikGapps/nikgapps.log"
}

copy_file() {
  mkdir -p "$(dirname "$3")"
  addToLog "- Unzipping $1"
  addToLog "  -> copying $2"
  addToLog "  -> to $3"
  unzip -o "$1" "$2" -p >"$3"
}

get_file_prop() {
  grep -m1 "^$2=" "$1" | cut -d= -f2
}

# Read the config file from (Thanks to xXx @xda)
ReadConfigValue() {
  value=$(sed -e '/^[[:blank:]]*#/d;s/[\t\n\r ]//g;/^$/d' "$2" | grep "^$1=" | cut -d'=' -f 2)
  echo "$value"
  return $?
}

InstallPackage() {
  value=1
  pkgFile="/tmp/$2.zip"
  pkgContent="pkgContent"
  if [ -f "$nikgapps_config_file_name" ]; then
    value=$(ReadConfigValue "$2" "$nikgapps_config_file_name")
  fi
  addToLog " "
  addToLog "- Working for $2"
  addToLog "- Config Value is $value"
  if [ "$value" == "" ]; then
    value=1
  fi
  addToLog "- Updated Config Value is $value"
  if [ "$value" -eq 0 ]; then
    ui_print "x Skipping $2"
  else
    ui_print "- Installing $2"
    copy_file "$1" "Packages/$2.zip" "$pkgFile"
    copy_file "$pkgFile" "installer.sh" "/tmp/$pkgContent/installer.sh"
    chmod 755 /tmp/$pkgContent/installer.sh
    # shellcheck source=src/installer.sh
    . "/tmp/$pkgContent/installer.sh" "$value" "$nikgapps_config_file_name"
  fi
}

grep_prop() {
  local REGEX="s/^$1=//p"
  shift
  local FILES=$@
  [ -z "$FILES" ] && FILES='/system/build.prop'
  sed -n "$REGEX" $FILES 2>/dev/null | head -n 1
}

beginswith() {
  case $2 in
  "$1"*)
    echo true
    ;;
  *)
    echo false
    ;;
  esac
}

# Device Functions

findDevice() {
  # Get device name any which way we can
  for field in ro.omni.device ro.product.device ro.build.product ro.product.name; do
    device_name="$(grep_prop "$field")"
    addToLog "$field has device_name as $device_name"
    if [ "${#device_name}" -ge "2" ]; then
      break
    fi
    device_name="Bad ROM/Recovery"
  done
  addToLog "- Device code in Recovery: $device_name"
  #  if [ $device_name == "Bad ROM/Recovery" ]; then
  #    abort "Make Sure you flash NikGapps after you flash a proper Rom"
  #  fi
}

ShowDeviceInfo() {
  ui_print " "
  ui_print "--> Fetching Device Information"
#  findDevice
  device=$(get_file_prop "$system/build.prop" "ro.product.system.device")
  ui_print "- Device code: $device"
  if [ -z "$device" ]; then
    abort "NikGapps not supported for your device yet!"
  fi
  sdkVersion=$(get_file_prop "$system/build.prop" "ro.build.version.sdk")
  ui_print "- SDK Version: $sdkVersion"
  androidVersion=$(get_file_prop "$system/build.prop" "ro.build.version.release")
  ui_print "- Android Version: $androidVersion"
  model=$(get_file_prop "$system/build.prop" "ro.product.system.model")
  addToLog "- Model: $model"
  case "$androidVersion" in
  "10")
    product="/product"
    ;;
  "9")
    product=""
    ;;
  "*")
    product=""
    ;;
  esac
}

# Termination

abort() {
  ui_print "$1"
  addToLog "$1"
  #  recovery_cleanup
  exitInstall
  exit 1
}

# Debloating

rmv() {
  addToLog "Removing $1"
  rm -rf "$1"
}

Debloat() {
  debloaterFilesPath="DebloaterFiles"
  debloaterRan=0
  if [ -f "$debloater_config_file_name" ]; then
    addToLog "- Debloater.config found!"
    g=$(sed -e '/^[[:blank:]]*#/d;s/[\t\n\r ]//g;/^$/d' "$debloater_config_file_name")
    for i in $g; do
      if [ $debloaterRan == 0 ]; then
        ui_print " "
        ui_print "--> Running Debloater"
      fi
      value=$($i | grep "^WipeDalvikCache=" | cut -d'=' -f 1)
      if [ "$i" != "WipeDalvikCache" ]; then
        addToLog "- Deleting $i"
        if [ -z "$i" ]; then
          ui_print "Cannot delete blank folder!"
        else
          debloaterRan=1
          startswith=$(beginswith / "$i")
          ui_print "x Removing $i"
          if [ "$startswith" == "false" ]; then
            echo "debloat=app/$i" >>/tmp/addon/$debloaterFilesPath
            echo "debloat=priv-app/$i" >>/tmp/addon/$debloaterFilesPath
            addToLog "- value of i is $i"
            rmv $system"/app/"$i
            rmv $system$product"/app/"$i
            rmv $system"/priv-app/"$i
            rmv $system$product"/priv-app/"$i
          else
            rmv "$i"
            echo "debloat=$i" >>/tmp/addon/$debloaterFilesPath
          fi
        fi
      else
        addToLog "- WipeDalvikCache config found!"
      fi
    done
    if [ $debloaterRan == 1 ]; then
      . /tmp/AFZCScripts/addon "$OFD" "Debloater" "/tmp/addon/$debloaterFilesPath"
      cp -f "$system/addon.d/Debloater.sh" "$logDir/Debloater.sh"
      cp -f "/tmp/addon/$debloaterFilesPath" "$logDir/Debloater.addon"
      rmv "/tmp/addon/$debloaterFilesPath"
    fi
  else
    addToLog "- Debloater.config not found!"
    copy_file "$ZIPFILE" "afzc/debloater.config" "/sdcard/NikGapps/debloater.config"
  fi
}

SetupTools() {
  #  sleep 1
  makeDir
  addToLog "- System is $system before setup"
  setup_env
  ui_print "- System is $system"
  ShowDeviceInfo
  nikgappsConfig="/sdcard/NikGapps/nikgapps.config"
  if [ ! -f $nikgappsConfig ]; then
    copy_file "$ZIPFILE" "afzc/nikgapps.config" "/sdcard/NikGapps/nikgapps.config"
    addToLog "nikgapps.config is copied to $nikgappsConfig"
  fi
  find_config
  #  Debloat
  addToLog "- nikgapps.config found in $nikgapps_config_file_name"
  addToLog "- debloater.config found in $debloater_config_file_name"
  ui_print " "
  #  sleep 1
  check_if_system_mounted_rw
  ui_print "--> Starting the install process"
}

exitInstall() {
  ui_print " "
  wipedalvik=$(ReadConfigValue "WipeDalvikCache" "$nikgapps_config_file_name")
  #  wipedalvik=$(ReadConfigValue "WipeDalvikCache" "$debloater_config_file_name")
  addToLog "- WipeDalvikCache value: $wipedalvik"
  if [ "$wipedalvik" != 0 ]; then
    ui_print "- Wiping dalvik-cache"
    rm -rf "/data/dalvik-cache"
  fi
  rm -rf "$system/nikgapps.config"
  ui_print "- Finished Installation"
  ui_print " "
  copyLogs
  restore_env
}

copyLogs() {
  ui_print "- Copying logs to $nikGappsDir/logs"
  cp -f "$recoveryLog" "$logDir/recovery.log"
  cp -f "$nikGappsLog" "$logDir/NikGapps.log"
  cp -f "$system/build.prop" "$logDir/build.prop"
  cp -f "$debloater_config_file_name" "$logDir/debloater.config"
  cp -f "$nikgapps_config_file_name" "$logDir/nikgapps.config"
  cd $logDir
  rm -rf $nikGappsDir/logs
  tar -cz -f "/tmp/$nikGappsLogFile" *
  mkdir -p $nikGappsDir/logs
  cp -f /tmp/"$nikGappsLogFile" $nikGappsDir/logs/"$nikGappsLogFile"
  cd /
}
