#!/bin/bash
# -*- coding: utf-8; indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
# vim:fileencodings=utf-8:expandtab:tabstop=4:shiftwidth=4:softtabstop=4

OEMLIB=${OEMLIB:-'/usr/share/volatile'}
. $OEMLIB/common.sh
. $OEMLIB/oem-common.sh

TASKDIR=
KEYWORD=
EXCLUDE=kylin

generate_pkg_list()
{
    local _task=$(find $1 -type f)
    local _list=
    local _keyword=${KEYWORD:-"apt_install|apt_install_oobe|PREREQ|PREREQ_DKMS|PREREQ_WORKAROUND"}
    local _reserve="for|while"

    if [ -n "$EXCLUDE" ]; then
        local _t
        for t in $_task; do
            if echo $t | grep -qE "($EXCLUDE)"; then
                continue
            fi
            _t="$_t $t"
        done
        _task=$(echo $_t)
    fi

    for f in $_task; do
        while read line
        do
            if echo $line | grep -q '='; then
                eval $line
                _list="$_list $(eval echo \$$(echo $line | grep -oE "($_keyword)"))"
            else
                _list="$_list $(eval echo $line | sed -r "s/$_keyword//")"
            fi
        done < <(grep -Eh "($_keyword)" $f | sed -r -e "/#/d" -e "/($_reserve)/d")
    done
    echo $_list
}

while [ "$1" ]; do
    case "$1" in
        --enable-kylin)
            . $OEMLIB/kylin.sh
            EXCLUDE=
        ;;
        -k|--keyword)
            shift
	    [ -z $KEYWORD ] && \
                KEYWORD=$1 || \
                KEYWORD="$KEYWORD|$1"
        ;;
        --debug)
            set -x
        ;;
        *)
            [ -n $1 ] && \
                TASKDIR=$1
        ;;
    esac
    shift
done

list=
for task in ${TASKDIR:-ubiquity-starttask ubiquity-successtask task}
do
    taskdir=$OEMLIB/${task##*/}
    list=$(echo "$list $(generate_pkg_list $taskdir)")
done
echo $list
