#!/bin/sh

ROOT_PREFIX=""
ARCH=$(dpkg --print-architecture)
if [ "$ARCH" = "iphoneos-arm" ]; then
   if [ -L "/var/jb" ]; then
      # get symlink target
      # xina support
      destination=$(readlink -f /var/jb)
      if [ "$destination" != "/jb" ]; then
         ROOT_PREFIX="$destination"
      fi
   fi

   base_ver=14.0
   ver=$(sw_vers -productVersion)
   
   if [ "$(printf %b $base_ver\\n$ver | sort -V | tail -1)" = "$base_ver" ]
   then # version < 14.0
      rm -rf $ROOT_PREFIX/Applications/CraneApplication.app
   else # version >= 14.0
      rm -rf $ROOT_PREFIX/Applications/CraneApplication_Legacy.app
   fi
else
   ROOT_PREFIX="/var/jb"
   # rootless has no legacy app
fi

chown root:wheel $ROOT_PREFIX/Library/LaunchDaemons/com.opa334.cranehelperd.plist
chmod 644 $ROOT_PREFIX/Library/LaunchDaemons/com.opa334.cranehelperd.plist

chown root:wheel $ROOT_PREFIX/usr/local/libexec/cranehelperd
chmod 755 $ROOT_PREFIX/usr/local/libexec/cranehelperd

chown root:wheel $ROOT_PREFIX/usr/local/bin/cranehelperd_start
chmod 06775 $ROOT_PREFIX/usr/local/bin/cranehelperd_start

launchctl load $ROOT_PREFIX/Library/LaunchDaemons/com.opa334.cranehelperd.plist 2> /dev/null

killall runningboardd 2> /dev/null
killall -9 containermanagerd 2> /dev/null
killall cfprefsd 2> /dev/null
killall -9 securityd 2> /dev/null
killall pkd 2> /dev/null
killall -9 apsd 2> /dev/null
killall -9 lsd 2> /dev/null
killall -9 accountsd 2> /dev/null
killall -9 gamed 2> /dev/null

exit 0