#!/system/bin/sh

ch_con() {
  chcon u:object_r:system_file:s0 $1
}

ch_con_ext() {
  chcon $2 $1
}

ln_ext() {
  ln -s $1 $2
}

set_perm() {
  chown $1.$2 $4
  chown $1:$2 $4
  chmod $3 $4
  ch_con $4
  if [ ! -z $5 ]; then
    ch_con_ext $4 $5
  fi
}

cp_perm() {
  if [ -f $5 ]; then
    rm $5
  fi
  cat $4 > $5
  set_perm $1 $2 $3 $5 $6
}

install_and_link() {
  TARGET=$1
  XPOSED="${1}_xposed"
  BACKUP="${1}_original"
  if [ ! -f "/tmp/xposed/$XPOSED" ]; then
    return
  fi
  cp_perm $2 $3 $4 /tmp/xposed/$XPOSED $XPOSED $5
  if [ ! -f $BACKUP ]; then
    mv $TARGET $BACKUP
    ln_ext $XPOSED $TARGET
  fi
}

install_overwrite() {
  TARGET=$1
  if [ ! -f "/tmp/xposed/$TARGET" ]; then
    return
  fi
  BACKUP="${1}.orig"
  NO_ORIG="${1}.no_orig"
  if [ ! -f $TARGET ]; then
    echo -n > $NO_ORIG
  elif [ ! -f $BACKUP -a ! -f $NO_ORIG ]; then
    mv $TARGET $BACKUP
  fi
  cp_perm $2 $3 $4 /tmp/xposed/$TARGET $TARGET $5
}

mount -o rw,remount /system
mount -o rw,remount /

mkdir /tmp
cd /tmp
rm -rf xposed
mkdir xposed
cd xposed
cp -r /data/local/tmp/system system

cp_perm 0 0 0644 /tmp/xposed/system/xposed.prop /system/xposed.prop
cp_perm 0 0 0644 /tmp/xposed/system/framework/XposedBridge.jar /system/framework/XposedBridge.jar

install_and_link /system/bin/app_process32                0 2000 0755 u:object_r:zygote_exec:s0
install_overwrite /system/bin/dex2oat                     0 2000 0755 u:object_r:dex2oat_exec:s0
install_overwrite /system/bin/oatdump                     0 2000 0755
install_overwrite /system/bin/patchoat                    0 2000 0755 u:object_r:dex2oat_exec:s0
install_overwrite /system/lib/libart.so                   0    0 0644
install_overwrite /system/lib/libart-compiler.so          0    0 0644
install_overwrite /system/lib/libart-disassembler.so      0    0 0644
install_overwrite /system/lib/libxposed_art.so            0    0 0644
install_overwrite /system/lib/libsigchain.so              0    0 0644
