#!/bin/bash

# A functions for scanning
# (c) 2008 Michal Vyskocil
#

# ${1} - temp dir
function clean() {
    if [[ -d ${1} ]]; then
        rm -rf ${1}
    fi
}

# #{1} - root
# ${@} - the iname patterns for find
function multiple_find() {

    local root patterns find_args
    root=${1}
    shift 1
    patterns=${@}

    if [[ $(echo ${patterns} | wc -w) -eq 1 ]]; then
        find_args="-iname ${patterns}"
    else
        find_args="-iname ${1}"
        shift 1
        patterns=${@}
        for pattern in ${patterns}; do
            find_args=${find_args}" -or -iname ${pattern}"
        done
    fi
    find ${root} ${find_args}
}

# A common function for scanning of modules
# Usage: scan RPMS_ROOT INDEX_FILE FILE_PATTERN STANDARD_DIRS_PATTERN
# $1 - directory with rpms
# $2 - name of index file
# $3 - file pattern to find
# $4 - standard dirs_pattern
function scan() {

    local rpms_root index_file tmp rpm_base_name standard_dirs_pattern

    rpms_root=${1}
    index_file=${2}
    standard_dirs_pattern=${3}
    shift 3
    file_pattern=${@}

    rm -rf ${index_file}
    touch ${index_file}

    cat ${rpms_root}/find-name-rpm | while read RPM; do

        tmp=$(mktemp --directory -t scout_scan.XXXXXXX)
        trap "clean ${tmp}" INT
        
        rpm_base_name=$(basename ${RPM})
        if [[ -z "$(rpm2cpio ${rpms_root}/${RPM} | cpio -t ${file_pattern})" ]]; then
            continue
        fi

        pushd ${tmp}

        rpm2cpio ${rpms_root}/${RPM} | cpio -i --verbose --make-directories ${file_pattern}

        for file in $(multiple_find . ${file_pattern}); do

            if [[ ! -z "${standard_dirs_pattern}" ]]; then
                if [[ ! $(echo ${file} | grep ${standard_dirs_pattern}) ]]; then
                    echo The ${file} is not in some of standard modules dir ... skipping
                    continue
                fi
            fi

            RPM=${RPM##*/}  # delete a path before
            RPM=${RPM%%.*}  # delete an extension
            write_row ${RPM} ${file} ${index_file} ${standard_dirs_pattern}

        done

        popd

        clean ${tmp}

    done

    rm -f ${index_file}.lzma
    lzma ${index_file}
}

scan_one_mode() {
    local mode=$1
    local release=$2
    local out=$3
    scan_$mode /work/CDs/all/full-$release-x86_64/suse $(pwd)/$mode-$out.txt
}

scan_all_mode() {
    local mode=$1
    scan_one_mode $mode sle11-sp4 sle11sp4
    scan_one_mode $mode sle12-sp1 sle12sp1
}
