VIPERFXPACKAGE="com.pittvandewitt.viperfx"

ui_print "- Installing ViPER4Android FX $(grep_prop version $MODPATH/module.prop)..."
APK_INSTALL_FOLDER="/data/local"
(
  cp -f "$MODPATH/system/app/ViPER/ViPER.apk" "$APK_INSTALL_FOLDER/ViPER.apk"
  pm install $APK_INSTALL_FOLDER/ViPER.apk >/dev/null 2>&1
  RET=$?
  rm "$APK_INSTALL_FOLDER/ViPER.apk"
  exit $RET
) || ui_print "  Failed to install ViPER4Android FX $(grep_prop version $MODPATH/module.prop)!"

ui_print "- Configuring ViPER4Android FX"
VIPERFXPREFS="$(pm dump $VIPERFXPACKAGE | grep dataDir | head -n 1 | cut -d'=' -f2)"
VIPERFXPREFSOWNER="$(stat -c '%U' "$VIPERFXPREFS")"
VIPERFXSHAREDPREFS="$VIPERFXPREFS/shared_prefs"
[ ! -d "$VIPERFXSHAREDPREFS" ] && mkdir "$VIPERFXSHAREDPREFS"
cp -f "$MODPATH/com.pittvandewitt.viperfx_preferences.xml" "$VIPERFXSHAREDPREFS/${VIPERFXPACKAGE}_preferences.xml"
chown -R $VIPERFXPREFSOWNER:$VIPERFXPREFSOWNER "$VIPERFXPREFS"
rm "$MODPATH/com.pittvandewitt.viperfx_preferences.xml"

PACKAGE_NAME="com.android.musicfx"
if [ -n "$(pm list packages | grep $PACKAGE_NAME)" ]; then
  ui_print "- Disabling $PACKAGE_NAME"
  if [ -n "$(pm list packages -d | grep $PACKAGE_NAME)" ]; then
    ui_print "  $PACKAGE_NAME is already disabled"
  else 
    pm disable-user $PACKAGE_NAME >/dev/null 2>&1
  fi
fi

ui_print "- Patching audio_effects.xml"
mkdir -p $MODPATH/system/vendor/etc
AUDIO_EFFECTS_FILE=$MODPATH/system/vendor/etc/audio_effects.xml
cp -f /vendor/etc/audio_effects.xml $AUDIO_EFFECTS_FILE
sed -i "/v4a_standard_fx/d" $AUDIO_EFFECTS_FILE
sed -i "/v4a_fx/d" $AUDIO_EFFECTS_FILE
sed -i "/<libraries>/ a\        <library name=\"v4a_fx\" path=\"libv4a_fx.so\"\/>" $AUDIO_EFFECTS_FILE
sed -i "/<effects>/ a\        <effect name=\"v4a_standard_fx\" library=\"v4a_fx\" uuid=\"41d3c987-e6cf-11e3-a88a-11aba5d5c51b\"\/>" $AUDIO_EFFECTS_FILE

ui_print "- Setting Permissions"
set_perm_recursive $MODPATH 0 0 0755 0644
if [ -d $MODPATH/system/vendor ]; then
  set_perm_recursive $MODPATH/system/vendor 0 0 0755 0644 u:object_r:vendor_file:s0
  [ -d $MODPATH/system/vendor/app ] && set_perm_recursive $MODPATH/system/vendor/app 0 0 0755 0644 u:object_r:vendor_app_file:s0
  [ -d $MODPATH/system/vendor/etc ] && set_perm_recursive $MODPATH/system/vendor/etc 0 0 0755 0644 u:object_r:vendor_configs_file:s0
  [ -d $MODPATH/system/vendor/overlay ] && set_perm_recursive $MODPATH/system/vendor/overlay 0 0 0755 0644 u:object_r:vendor_overlay_file:s0
  for FILE in $(find $MODPATH/system/vendor -type f -name *".apk"); do
    [ -f $FILE ] && chcon u:object_r:vendor_app_file:s0 $FILE
  done
fi
set_permissions