#!/usr/bin/env bash

usage_list=("-nativever <Native binary version>: Version of native binaries.")
usage_list+=("-commithash <Git commit hash>: Current commit hash of the repo at build time.")

set -e

__scriptpath="$(cd "$(dirname "$0")"; pwd -P)"
__RepoRootDir="$(cd "$__scriptpath"/../../..; pwd -P)"

__BuildArch=x64
__TargetOS=Linux
__BuildType=Debug
__CMakeArgs=""
__Compiler=clang
__CompilerMajorVersion=
__CompilerMinorVersion=
__CrossBuild=0
__IsMSBuildOnNETCoreSupported=0
__PortableBuild=1
__RootBinDir="$__RepoRootDir/artifacts"
__SkipConfigure=0
__SkipGenerateVersion=0
__StaticLibLink=0
__UnprocessedBuildArgs=
__VerboseBuild=false
__native_ver=
__commit_hash=

handle_arguments() {

    case "$1" in
        nativever|-nativever)
            __native_ver="$2"
            __ShiftArgs=1
            ;;

        commithash|-commithash)
            __commit_hash="$2"
            __ShiftArgs=1
            ;;

        *)
            __UnprocessedBuildArgs="$__UnprocessedBuildArgs $1"
    esac
}

source "$__RepoRootDir"/eng/native/build-commons.sh

# Set dependent variables
__LogsDir="$__RootBinDir/log"
__MsbuildDebugLogsDir="$__LogsDir/MsbuildDebugLogs"

# Set the remaining variables based upon the determined build configuration
__DistroRidLower="$(echo $__DistroRid | tr '[:upper:]' '[:lower:]')"
__BinDir="$__RootBinDir/bin/$__DistroRidLower.$__BuildType"
__IntermediatesDir="$__RootBinDir/obj/$__DistroRidLower.$__BuildType"

export __BinDir __IntermediatesDir

__CMakeArgs="-DCLI_CMAKE_NATIVE_VER=\"$__native_ver\" $__CMakeArgs"
__CMakeArgs="-DCLI_CMAKE_PKG_RID=\"$__DistroRid\" -DCLI_CMAKE_COMMIT_HASH=\"$__commit_hash\" $__CMakeArgs"

if [[ "$__PortableBuild" == 1 ]]; then
    __CMakeArgs="-DCLI_CMAKE_PORTABLE_BUILD=1 $__CMakeArgs"
fi

# Specify path to be set for CMAKE_INSTALL_PREFIX.
# This is where all built binaries will be copied to.
__CMakeBinDir="$__BinDir"
export __CMakeBinDir

# Make the directories necessary for build if they don't exist
setup_dirs

# Check prereqs.
check_prereqs

# Build the installer native components.
# note the third argument, tryrun_dir is empty for installers
build_native "$__BuildArch" "$__scriptpath" "" "$__IntermediatesDir" "installer component"
