#!/bin/sh

#echo "copy2scp pkg_output pkg_name server out_path out_old"

PKG_OUTPUT=$1
PKG_NAME=$2
SERVER=$3
OUT_PATH=$4
OUT_OLD=$5
EXCEPTION=$6

echo "#### copy2scp $PKG_OUTPUT,$PKG_NAME,$SERVER,$OUT_PATH,$OUT_OLD"

if [ -n "$EXCEPTION" ]; then
    SRC=`find $PKG_OUTPUT -name "$PKG_NAME*" | grep -v "${EXCEPTION}"`
else
    SRC=`find $PKG_OUTPUT -name "$PKG_NAME*"`
fi

if [ -z "$SRC" ]; then
    echo "Package file not found. [$PKG_NAME]"
    exit 1
fi

CNT=`echo "$SRC" | wc -l`
if [ $CNT -ne 1 ]; then
    echo "Two or more package exist.[$PKG_NAME]"
    exit 1
fi

`scp $SRC $SERVER:$OUT_OLD`
`which pkg_create 2>&1 > /dev/null`
if [ $? -eq 0 ]; then
    RM_FILE=`ssh -l root -n $SERVER "find $OUT_PATH/$PKG_NAME*.tbz  | grep -v \"${EXCEPTION}\"" > /dev/null 2>&1`
    if [ -n "$RM_FILE" ]; then
        `ssh -l root -n $SERVER "rm $RM_FILE" > /dev/null 2>&1`
    fi
    `scp $SRC $SERVER:$OUT_PATH/$PKG_NAME.tbz`
else
    `ssh -l root -n $SERVER "rm $OUT_PATH/$PKG_NAME*.txz" > /dev/null 2>&1`
    `scp $PKG_OUTPUT/* $SERVER:$OUT_PATH`
fi

