#!/bin/bash

shopt -s nullglob

finish() {
  f="${1}"
  [[ -z "${f}" || -z "${CYDIA}" ]] && return
  cydia=(${CYDIA})
  [[ ${cydia[1]} -eq 1 ]] || return
  echo "finish:${f}" >&${cydia[0]}
}

echo '[*] Removing beta profile configurations...'
rm -f '/var/mobile/Library/Preferences/com.apple.MobileAsset.plist'
rm -f '/var/Managed Preferences/mobile/com.apple.MobileAsset.plist'

echo '[*] Re-enabling OTA daemons...'
for f in mobile.softwareupdated OTATaskingAgent softwareupdateservicesd; do
  f="/System/Library/LaunchDaemons/com.apple.$f.plist"
  if [[ ! -f "$f" ]] && [[ -f "${f%.plist}.disabled" ]]; then
    mv "${f%.plist}.disabled" "$f"
  fi
  launchctl unload "$f" 2>/dev/null
  launchctl load -w "$f" 2>&1 | grep -v 'service already loaded' >&2
done

echo '[*] Fixing up preboot...'
boot_manifest_hash=$(ioreg -p IODeviceTree -l | awk -F'[<>]' '/boot-manifest-hash/ { print toupper($2) }')
if [[ -e /private/preboot/active ]]; then
    echo '/private/preboot/active already exists. Nothing to do.'
else
    echo "Writing $boot_manifest_hash to /private/preboot/active"
    printf '%s' "$boot_manifest_hash" > /private/preboot/active  # No newline at the end is very important!
fi

echo '[*] Disabling unc0ver OTA blocker...'
killall -9 cfprefsd unc0ver
for f in /var/mobile/Containers/Data/Application/*/Library/Preferences/science.xnu.undecimus.plist; do
  plutil -key DisableAutoUpdates -type bool -value false "$f"
done
killall -9 cfprefsd unc0ver

echo '[*] Reverting changes made by unc0ver...'
if mount | grep -q /private/var/MobileSoftwareUpdate/mnt1/dev; then
  echo '[-] KernBypass is installed. Please uninstall it and reboot, then reinstall OTAEnabler.' >&2
  finish reboot
  exit 0
fi
files=(
  /var/MobileAsset/Assets/com_apple_MobileAsset_SoftwareUpdate
  /var/MobileAsset/Assets/com_apple_MobileAsset_SoftwareUpdateDocumentation
  /var/MobileAsset/AssetsV2/com_apple_MobileAsset_SoftwareUpdate
  /var/MobileAsset/AssetsV2/com_apple_MobileAsset_SoftwareUpdateDocumentation
  /var/MobileSoftwareUpdate/MobileAsset/AssetsV2
)
chflags -R noschg,nouchg,norestricted /var/MobileAsset /var/MobileSoftwareUpdate
for f in "${files[@]}"; do
  rm -rf "$f"
  install -m 755 -o root -g wheel -d "$f"
done

echo 'Done! Please do an ldrestart or userspace reboot for the changes to take effect.'
finish reboot
