[ -z $BUILD_TARGET ] && echo "Environment \$BUILD_TARGET variable MUST be set" && exit 1

LIB_SRC=lib/$BUILD_TARGET
PREBUILD_SRC=prebuild/$BUILD_TARGET/ffmpeg/include/libavutil
[ ! -f $PREBUILD_SRC/avutil.h ] && echo "Build FFmpeg first" && exit 1

INC_SRC=include/core
INC_DST=client-sdk/include/core
mkdir -p $INC_DST/include
mkdir -p $INC_DST/impl
cp $INC_SRC/*.h $INC_DST/
cp $INC_SRC/include/*.h $INC_DST/include/
cp $INC_SRC/impl/*.h $INC_DST/impl/

LIB_DST=client-sdk/lib/$BUILD_TARGET
mkdir -p $LIB_DST

PREBUILD_DST=client-sdk/prebuild/$BUILD_TARGET/ffmpeg/include/libavutil
mkdir -p $PREBUILD_DST
cp $PREBUILD_SRC/*.h $PREBUILD_DST

ARCH=x64
if [ "$BUILD_TARGET" = "x86_64-linux" ]; then
    [ ! -f $LIB_SRC/libVNMediaClient_static.a ] && echo "No target libraries exist" && exit 1
    OS=linux
    cp $LIB_SRC/libVNMediaClient_static.a $LIB_DST
elif [ "$BUILD_TARGET" = "x86_64-darwin" ]; then
    [ ! -f $LIB_SRC/libVNMediaClient_static.a ] && echo "No target libraries exist" && exit 1
    OS=darwin
    cp $LIB_SRC/libVNMediaClient_static.a $LIB_DST
elif [ "$BUILD_TARGET" = "x86_64-mingw32" ]; then
    [ ! -f $LIB_SRC/VNMediaClient.dll ] && echo "No target libraries exist" && exit 1
    OS=win32
    cp $LIB_SRC/VNMediaClient.* $LIB_DST
    wget -r -nH --cut-dirs=3 --no-parent --reject="index.htm*" https://ftp.videonext.net/private/native-addons/vn_player/libs/$BUILD_TARGET/ || (mkdir -p libs/$BUILD_TARGET && wget https://ftp.videonext.net/private/native-addons/vn_player/libs/$BUILD_TARGET/D3DX9_43.dll -P libs/$BUILD_TARGET)
else
    ARCH=
    OS=
fi

git log | head -1 | cut -c8-19 > git_commit

# let's modify package.json
[ -n "$ARCH" -a -n "$OS" ] && \
# specify name
perl -0777 -i.orig -pe "s/client-sdk-prebuilt/vn-sdk-prebuilt-$OS-x86_64/igs" package.json && \
# specify cpu and os
perl -0777 -i -pe "s/\n}/,\n  \"cpu\": [\n    \"$ARCH\"\n  ],\n  \"os\": [\n    \"$OS\"\n  ]\n}/igs" package.json
