#!/bin/bash
ARCH=${1:-64}
LIBXCODER_PATH=$(realpath ${2:-~/FFmpegXcoder/libxcoder})
FFMPEG_PATH=$(realpath ${3:-~/FFmpegXcoder/FFmpeg-n4.3})
ANDROID_VER=${4:-9}
NIDEC_PATH=$(realpath ${5:-~/FFmpegXcoder/AOSP/Android${ANDROID_VER}/nidec})

function error_exit() {
    echo Error
    exit 1
}

#unzip android_ndk and android_sdk
file_list=("/home/$USER/android-ndk-r21d" "/home/$USER/android/android-sdk-linux" "./android-ndk-r*" "./android-sdk-linux_r*")
for i in "${file_list[@]}";do
    if [ -d "$i" ];then
        echo "remove $i"
        rm -rf $i
    fi
done

if [ -f ./android-ndk-r*-linux-x86_64.zip ]; then
    fname=$(ls ./android-ndk-r*-linux-x86_64.zip | tail -n 1)
    dirname=$(basename ${fname%-linux-x86_64.zip})
    unzip $fname -d .
    export ANDROID_NDK_ROOT=$(pwd)/$dirname
else
    fname=$(ls ~/android/android-ndk-r*-linux-x86_64.zip | tail -n 1)
    dirname=$(basename ${fname%-linux-x86_64.zip})
    unzip $fname -d ~
    export ANDROID_NDK_ROOT=/home/$USER/$dirname
fi
if [ -f ./android-sdk_r*-linux.tgz ]; then
    fname=$(ls ./android-sdk_r*-linux.tgz | tail -n 1)
    tar -zxf $fname -C .
    export ANDROID_HOME=$(pwd)/android-sdk-linux
else
    fname=$(ls ~/android/android-sdk_r*-linux.tgz | tail -n 1)
    tar -zxf $fname -C ~/android/
    export ANDROID_HOME=/home/$USER/android/android-sdk-linux
fi

export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig

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

# Build Libxcoder & FFmpeg
#sudo -s -E << BASH
cd /home/$USER/$WORK_DIR && echo OK || error_exit
source build/envsetup.sh &> /dev/null && echo OK || error_exit
lunch $LUNCH_CMD &> /dev/null && echo OK || error_exit

rm ./hardware/interfaces/nidec -rf
cp $NIDEC_PATH hardware/interfaces/ -r && echo OK || error_exit
mmm ./hardware/interfaces/nidec/1.0/ && echo OK || error_exit

rm ./external/libxcoder/source/libxcoder -rf
cp $LIBXCODER_PATH ./external/ -r && echo OK || error_exit
mmm ./external/libxcoder/source && echo OK || error_exit
sudo rm /usr/local/lib/libxcoder.so && echo OK || error_exit
sudo cp out/target/product/$GENERIC_DIR/system/$LIB_DIR/libxcoder.so /usr/local/lib/ && echo OK || error_exit
cd $LIBXCODER_PATH && echo OK || error_exit
sudo make clean &> /dev/null || true
bash ./build.sh --android && echo OK || error_exit
cd $FFMPEG_PATH && echo OK || error_exit
sudo make clean &> /dev/null || true
echo "bash build_ffmpeg.sh -a --shared --quadra --android_arch \"$AARCH_NAME\""
bash build_ffmpeg.sh -a --shared --quadra --android_arch "$AARCH_NAME" && echo OK || error_exit
sudo make install && echo OK || error_exit
sudo ldconfig && echo OK || error_exit
