#!/bin/sh
#
# File listing of contents released through Qualcomm's CRM process
#
# 'lspack' is designed to be used with 'ls' and 'diff' to compare
# filesystem contents against packfiles.
#
# Note: only vendor/qcom/proprietary/* contents are released through CRM
#


# restrict output to files contained in the current sub-tree
unit=$(pwd | sed 's!^.*proprietary\/!!')
# ignore UNIX/Windows path separator differences
unit=$(echo ${unit} | sed 's!\/!\.!g')

qcom_root="vendor/qcom/proprietary"
packfile_dir="${qcom_root}/release/crm"


locate_packfiles ()
{
    packdir=$(pwd | sed "s!${qcom_root}.*!${packfile_dir}!")

echo $packdir

    if ! [ -d ${packdir} ] ; then
        echo "$0: fatal error, unable to find packfiles"
        exit 1
    fi
}

pack_listing ()
{
    pushd ${packdir} 2>&1 >/dev/null

    files=$(ls -R ship_*)
    if ! [ -z "${target_restrict}" ]; then
        files=$(ls -R ship_* | \
                    grep -e ${target_restrict} -e common_${variant_restrict})
    elif ! [ -z "${variant_restrict}" ]; then
        files=$(ls -R ship_* | grep ${variant_restrict})
    fi
    if [ -z "${files}" ]; then
        echo "$0: fatal no pack files found"
        exit 1
    fi

    for file in ${files}; do

        out=$(grep "${unit}" "${file}" |        \
            cut -f 2 -d ' '            |        \
            sed 's/^.*proprietary\\//' |        \
            grep ^${unit} | sed "s/^${unit}.//")

        if ! [ -z "${out}" ]; then

            if ! [ "${quiet}" = "y" ]; then
                echo "${packfile_dir}/${file}:"
            fi

            if [ "${one_column}" = "y" ]; then
                for one in ${out}; do
                    echo ${one}
                done
            else
                echo ${out}
            fi

            if ! [ "${quiet}" = "y" ]; then
                echo ""
            fi
        fi

    done

    popd 2>&1 >/dev/null
}


one_column='n'
quiet='n'

while getopts ":t::v:1q" opt; do
    case ${opt} in
    1)
        one_column='y'
        ;;
    q)
        quiet='y'
        ;;
    t)
        target_restrict=${OPTARG}
        ;;
    v)
        variant_restrict=$(echo ${OPTARG} | tr '[a-z]' '[A-Z]')
        ;;
    *)
cat <<USAGE
    Usage: lspack [-t target] [-v variant] [-q] [-1]

    List files included in Qualcomm's CRM release. Output is restricted
    to the current sub-tree.

    Optional arguments:

      -t target    target (e.g. msm8660_surf, msm7630_fusion, ...)
      -v variant   CRM variant (e.g. HY11, HY22, ...)
      -1           list one file per line
      -q           suppress whitespace and target/CRM variant info


    Display files in the current directory sub-tree which are included
    in the currently defined HY11, msm8660_surf pack file combination:

       $ lspack -q -1 -v HY11 -t msm8660

USAGE
        exit 1
        ;;
    esac
done

locate_packfiles
pack_listing

