#!/bin/bash

extract() {
    local prefix_to_remove=""
    local arg
    for arg in "$@"; do
        local toolchain_name
        for toolchain_name in ${bb_toolchain_names}; do
            local toolchain_prefix_var="${toolchain_name}_prefix"
            if [[ "${arg}" == "${!toolchain_prefix_var}/"* ]]; then
                prefix_to_remove="${!toolchain_prefix_var}/"
                break
            fi
        done
        if [[ -z "${prefix_to_remove}" ]]; then
            echo "WARNING: Could not find a matching prefix for extraction path ${arg}"
        fi
        local files=( $(compgen -G "${arg}") )
        local file
        for file in "${files[@]}"; do
            local CP_FLAGS=( "-av" )
            if [[ "${BB_PRINT_COMMANDS}" == "true" ]]; then
                CP_FLAGS+=( "-v" )
            fi

            local dest="${extract_dir}/${file##${prefix_to_remove}}"
            mkdir -p "$(dirname "${dest}")"
            cp "${CP_FLAGS[@]}" "${file}" "${dest}"
        done
    done
}

license_dir() {
    echo -n "${1}/share/licenses/${SRC_NAME}"
}

find_license_files() {
    # Build the list of known names for license files
    LICENSE_FILENAMES=()
    for bname in COPYING COPYRIGHT LICENCE LICENSE NOTICE; do
        for extension in "" .md .rtf .txt .MIT .BSD .GPL .GPLv2 .GPLv3; do
            # These are actually going to be options for `find`
            LICENSE_FILENAMES+=(-iname "${bname}${extension}" -o)
        done
    done
    # Remove the last OR
    unset 'LICENSE_FILENAMES[${#LICENSE_FILENAMES[@]}-1]'

    # Find the license files in $1 and print them out
    find "$1" -maxdepth 1 -type f \( "${LICENSE_FILENAMES[@]}" \) -print0 2>/dev/null
}

# Function to attempt to automatically install license files
auto_install_license() {
    if ! [[ -d "$(license_dir "${extract_dir}")" ]]; then
        # If there is a license directory installed in `${prefix}`, copy that over
        if [[ -d "$(license_dir "${prefix}")" ]]; then
            mkdir -p "$(dirname "$(license_dir "${extract_dir}")")"
            cp -Ra "$(license_dir "${prefix}")" "$(license_dir "${extract_dir}")"
        else
            # The license directory doesn't exist, let's find all licenses
            ROOTDIR="${WORKSPACE}/srcdir"
            readarray -d '' LICENSE_FILES < <(find_license_files "${ROOTDIR}")

            if [[ "${#LICENSE_FILES[@]}" == 0 ]]; then
                # If we didn't find any license files, try again if there is a single subdirectory of `srcdir`,
                # (excluding `patches`).  This allows us to easily unwrap single-directory srcdirs,
                # which is a very common scenario.
                readarray -d '' SUBDIRS < <(find "${ROOTDIR}" -mindepth 1 -maxdepth 1 -type d -not -path "${ROOTDIR}/patches" -print0 2>/dev/null)
                if [[ "${#SUBDIRS[@]}" == "1" ]]; then
                    readarray -d '' LICENSE_FILES < <(find_license_files "${SUBDIRS[0]}")
                fi
            fi

            if [[ "${#LICENSE_FILES[@]}" != 0 ]]; then
                install_license "${LICENSE_FILES[@]}"
            fi
        fi
    fi

    if [[ "$@" == "-c" ]]; then
        # If we pass the `-c` option, return code shows whether there is a license installed
        [[ -d "$(license_dir "${extract_dir}")" ]]
    fi
}
