#!/bin/bash
FW_REV=$1
ARCH=${2:-64}
FFMPEG_PATH=$(realpath ${3:-~/FFmpegXcoder/FFmpeg-n4.3})

if [ $ARCH = '64' ]
then
    WORK_DIR='android_work'
    LUNCH_CMD='aosp_x86_64-eng'
    GENERIC_DIR='generic_x86_64'
    LIB_DIR='lib64'
    AARCH_NAME='x86_64'
else
    WORK_DIR='android_work32'
    LUNCH_CMD='aosp_x86-eng'
    GENERIC_DIR='generic_x86'
    LIB_DIR='lib'
    AARCH_NAME='x86'
fi

#sudo -s -E << BASH
cd /home/$USER/$WORK_DIR && echo OK || echo Error
source build/envsetup.sh &> /dev/null && echo OK || echo Error
lunch $LUNCH_CMD &> /dev/null && echo OK || echo Error
adb root && adb remount && echo OK || echo Error

# we assume manifest and mediacodec.policy files are already in there since they don't change
adb push mediacodec.policy /system/etc/seccomp_policy/ && echo OK || echo Error
adb push manifest.xml vendor/ && echo OK || echo Error


adb push out/target/product/$GENERIC_DIR/system/$LIB_DIR/vndk-28/android.hardware.nidec\@1.0.so /system/lib/vndk-28/ && echo OK || echo Error
adb push out/target/product/$GENERIC_DIR/system/$LIB_DIR/android.hardware.nidec\@1.0.so /system/lib64/ && echo OK || echo Error
adb push out/target/product/$GENERIC_DIR/system/$LIB_DIR/android.hardware.nidec\@1.0.so /vendor/lib64/ && echo OK || echo Error
adb push out/target/product/$GENERIC_DIR/vendor/$LIB_DIR/hw/android.hardware.nidec\@1.0-impl.so /vendor/lib64/hw/ && echo OK || echo Error
adb push out/target/product/$GENERIC_DIR/vendor/$LIB_DIR/hw/android.hardware.nidec\@1.0-impl.so /vendor/lib64/ && echo OK || echo Error
adb push out/target/product/$GENERIC_DIR/vendor/bin/hw/android.hardware.nidec\@1.0-service /vendor/bin/hw/ && echo OK || echo Error
adb push out/target/product/$GENERIC_DIR/vendor/etc/init/android.hardware.nidec\@1.0-service.rc /vendor/etc/init/ && echo OK || echo Error


adb push out/target/product/$GENERIC_DIR/vendor/bin/ni_rsrc_mon /system/bin/ && echo OK || echo Error
adb push out/target/product/$GENERIC_DIR/vendor/bin/ni_rsrc_list /system/bin/ && echo OK || echo Error
# adb push out/target/product/$GENERIC_DIR/system/bin/ni_rsrc_mon /system/bin/
adb push out/target/product/$GENERIC_DIR/system/$LIB_DIR/libxcoder.so /system/$LIB_DIR/ && echo OK || echo Error
adb </dev/null shell ln -f -s /system/$LIB_DIR/libxcoder.so /system/$LIB_DIR/libxcoder.so.$FW_REV && echo OK || echo Error
adb push $FFMPEG_PATH/android/$AARCH_NAME/lib/* /system/$LIB_DIR/ && echo OK || echo Error
adb push $FFMPEG_PATH/android/$AARCH_NAME/bin/* /system/bin/ && echo OK || echo Error

adb reboot && echo OK || echo Error
sleep 10 && echo OK || echo Error
#BASH