#!/bin/sh

#echo "create pkg_metadir pkg_filelist pkg_output target"
PKG_META=$1
PKG_FILELIST=$2
PKG_OUTPUT=$3
TARGET=$4

if [ -n "$TARGET" ]; then
    KEY_PATH=`grep "${TARGET}-KEY-PATH=" ../.DEPLOYMENT_INFO |  sed -e "s/$(echo $TARGET)-KEY-PATH=//" `
    PKG_OUTPUT="$PKG_OUTPUT/$KEY_PATH"
else
    T=$PKG_OUTPUT;
    PKG_OUTPUT=""
    KEY_LIST=`grep "ALL-KEY-PATH=" ../.DEPLOYMENT_INFO | sed 's/ALL-KEY-PATH=//'`
    for v in $KEY_LIST; do
        P="$T/$v "
        PKG_OUTPUT="$PKG_OUTPUT$P" 
    done
fi

echo "### create package : $PKG_META, $PKG_FILELIST, $PKG_OUTPUT, $TARGET"

for v in $PKG_OUTPUT; do
    `mkdir -p $v`
    `which pkg_create 2>&1 > /dev/null`
    if [ $? -eq 0 ]; then
        PKG_MANIFESTF="$PKG_META/+MANIFEST"
        PKG_NAME=`grep "name: " $PKG_MANIFESTF | sed 's/name: //'`
        PKG_VER=`grep "version: " $PKG_MANIFESTF | sed 's/version: //'`
        #PKG_COMMENT=`grep -A1 "comment: " $PKG_MANIFESTF | sed -e '1d' | sed -e 's/^ *//g' | sed -e 's/\[/\\\[/' | sed -e 's/\]/\\\]/' | sed -e 's/ /\\\\ /g'` 
        PKG_PREFIX=`grep "prefix: " $PKG_MANIFESTF | sed 's/prefix: //'`
        PKG_ORIGIN=`grep "origin: " $PKG_MANIFESTF | sed 's/origin: //'`
        PKG_COMMENT="$PKG_META/COMMENT"
        PKG_DESC="$PKG_META/+DESC"
        PKG_PREINSTALL="$PKG_META/+PRE_INSTALL"
        PKG_POSTINSTALL="$PKG_META/+POST_INSTALL"
        
        #NAME=`echo "$v/$PKG_NAME-$PKG_VER" | sed -e 's/_/\\\\_/'`
        NAME=`echo "$v/$PKG_NAME-$PKG_VER"`
        #ORIGIN=`echo "$PKG_ORIGIN$PKG_VER" | sed -e 's/_/\\\\_/'`
        ORIGIN=`echo "$PKG_ORIGIN$PKG_VER"`
        echo "#### pkg_create -p $PKG_PREFIX -c $PKG_COMMENT -d $PKG_DESC -f $PKG_FILELIST -i $PKG_PREINSTALL -I $PKG_POSTINSTALL -o $ORIGIN $NAME"
        pkg_create -p $PKG_PREFIX -c $PKG_COMMENT -d $PKG_DESC -f $PKG_FILELIST -i $PKG_PREINSTALL -I $PKG_POSTINSTALL -o $ORIGIN $NAME
    else
        echo "#### pkg-static create -m $PKG_META -p $PKG_FILELIST -o $v"
        pkg-static create -m $PKG_META -p $PKG_FILELIST -o $v
        if [ $? -ne 0 ]; then
            exit 1
        fi
        pkg-static repo $v
    fi
done

