#!/bin/bash

# clean files first
if [ -f ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/package.zip ]; then
    rm ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/package.zip
fi

# init scripts directory
scriptsdir="$HOME/.qvmfix"

# get mode, local/online
mode=$1
if [ "$mode" = "" ]; then
    mode=local
fi

# trace
echo "qvmfix patch mode: $mode"

# generate and install patch
if [ "${QVMFIX_PATCH}" != "YES" ] && [ "$mode" == "local" ]; then

    # download and install patch scripts
    localdir=`git rev-parse --show-toplevel`/scripts/patcher
    if [ ! -d $scriptsdir ]; then
        echo "installing qvmfix scripts to $scriptsdir .."
        if [ -d $localdir ]; then
            cp -r $localdir $scriptsdir
        else
            git clone ssh://git@gitlab.qiyi.domain:10022/QYApmPods/qvmfix_scripts.git $scriptsdir
        fi
    else
        echo "updating qvmfix scripts in $scriptsdir .."
        if [ -d $localdir ]; then
            if [ -d $scriptsdir ]; then
                rm -rf $scriptsdir
            fi
            cp -r $localdir $scriptsdir
        elif [ ! -d "$scriptsdir/.git" ]; then
            rm -rf $scriptsdir
            git clone ssh://git@gitlab.qiyi.domain:10022/QYApmPods/qvmfix_scripts.git $scriptsdir
        else
            git -C $scriptsdir reset --hard
            git -C $scriptsdir pull origin master
        fi
    fi

    # link clang++ ..
    if [ ! -f $scriptsdir/llvm-16.0.0-rc1/bin/clang++ ]; then
        ln -s $scriptsdir/llvm-16.0.0-rc1/bin/clang $scriptsdir/llvm-16.0.0-rc1/bin/clang++
    fi
    if [ ! -f $scriptsdir/llvm-16.0.0-rc1/bin/clang-cpp ]; then
        ln -s $scriptsdir/llvm-16.0.0-rc1/bin/clang $scriptsdir/llvm-16.0.0-rc1/bin/clang-cpp
    fi
    if [ ! -f $scriptsdir/llvm-16.0.0-rc1/bin/clang-cl ]; then
        ln -s $scriptsdir/llvm-16.0.0-rc1/bin/clang $scriptsdir/llvm-16.0.0-rc1/bin/clang-cl
    fi

    # generate package.zip
    echo "generating to ${SRCROOT}/patch_output/package.zip .."
    $scriptsdir/generate.py -p ${SRCROOT} -o ${SRCROOT}/patch_output
    if [ $? != 0 ]; then
        exit -1
    fi

    # install package.zip
    echo "installing to ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/package.zip .."
    cp ${SRCROOT}/patch_output/generated/package.zip ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/package.zip
    if [ $? != 0 ]; then
        exit -1
    fi

    # done
    echo "done!"
fi

