#!/usr/bin/env bash
#
# crossclang
# A helper script to simplify cross-compilation
#
# sync-target-sdk is to be run on the target platform
# see prepare-target-sdk for details
#
# Copyright 2019 Christian Kohlschütter
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
showHelp=0
if [[ $# -eq 0 || "$1" == "-h" || "$1" == "--help" ]]; then
    showHelp=1
fi

no_libraries=0
sdkroot=
while [ $# -gt 0 ]; do
    arg="$1"
    shift
    case "$arg" in
        -L) no_libraries=1 ;;
        -*) showHelp=1 ;;
         *)
            if [ -n "$sdkroot" ]; then
                showHelp=1;
            else
                sdkroot="$arg";
            fi
            ;;
    esac
done

if [ -z "$sdkroot" ]; then
    showHelp=1
fi

if [ $showHelp -eq 1 ]; then
    cat >&2 <<EOT
USAGE: $0 [-L] <path-to-sdk>

OPTIONS:
  -L    Do not transfer libraries or frameworks

EOT
    exit 1
fi

targetConf="$sdkroot/target.conf"
if [ ! -f "$targetConf" ]; then
    echo "target.conf not found: $targetConf" >&2
    exit 1
fi

sdkroot=$(cd "$sdkroot"; pwd)

target_include_path=()
target_library_path=()
target_framework_path=()
IFS=$'\n'
source "$targetConf"

if [ $no_libraries -gt 0 ]; then
    target_library_path=()
    target_framework_path=()
fi

recursive_paths=()
recursive_paths+=("${target_include_path[@]}")
recursive_paths+=("${target_framework_path[@]}")

flat_paths=()
flat_paths+=("${target_library_path[@]}")

declare includeFile
declare -a paths
declare recursive=0

includeFile="$sdkroot/include-files.txt"
rm -f "$includeFile"

function add_paths() {
    for path in "${paths[@]}"; do
        if [[ -z "$path" || "$path" == "/" ]]; then
            continue
        fi
        dir="${path%/*}"
        sourcepath="$path"
        
        if [ $recursive -eq 0 ]; then
            find "$path" -mindepth 1 -maxdepth 1 -not -type d >> "$includeFile"
        else
            find "$path" -not -type d >> "$includeFile"
        fi
    done
}

paths=(${recursive_paths[@]})
recursive=1
add_paths

paths=(${flat_paths[@]})
recursive=0
add_paths

cd "$sdkroot/"
# rsync -avR --prune-empty-dirs --include-from="$includeFile" --exclude '*' / .
tar cvf - -C / -T "$includeFile" | tar xvf - -C .
rm "$includeFile"
