#!/bin/bash

# "patchme" script.

#  Copyright (c) 2010 Wind River Systems, Inc.

#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 2 as
#  published by the Free Software Foundation.

#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#  See the GNU General Public License for more details.

#  This script must be run from inside a Linux source directory

usage()
{
cat << EOF

    patchme [<machine>] [<meta_series>]

      <machine>: the name of the kernel machine to patch
 
      <meta_series>: the meta series that should be applied to the
                     tree. If it isn't passed, it will be located 
                     based on the branch name.

EOF
}

# find the meta directory
get_meta_dir()
{
    # if there's already a located and logged meta directory, just use that and
    # return. Otherwise, we'll look around to see what we can find.
    if [ -d ".metadir" ]; then
        md=`cat .metadir`
        echo $md
        return
    fi

    # determine the meta directory name
    meta_dir_options=`git ls-files -o --directory`
    for m in $meta_dir_options; do
	if [ -d "$m/cfg" ]; then
	    md=`echo $m | sed 's%/%%'`
	fi
    done

    # store our results where other scripts can quickly find the answer
    if [ -n "$md" ]; then
        echo "$md" > .metadir
    else
        mkdir ".$meta_branch"
        md=".$meta_branch"
        echo ".$meta_branch" > .metadir
    fi

    # return the directory to he caller
    echo $md
}

meta_branch=$KMETA
meta_dir=`get_meta_dir`

if [ -z "$1" ]; then
	usage
	exit
fi

while [ $# -gt 0 ]; do
	case "$1" in
	    --help)
		usage
		exit
		;;
	    --force)
		force=t
		;;
	    -v) verbose=t
		;;
	    *) break
		;;
	esac
	shift
done

ktgt=$1
meta_series=$2
CURRENT=`git branch |grep \*|sed 's/^\* //'`
if [ -z "$branch" ]; then
	branch=$CURRENT
fi


find_meta_series() {
	tgt=$1
	meta_series=`find $meta_dir/cfg/scratch -name "$tgt\-*meta"`
	if [ -z "$meta_series" ]; then
	    echo "ERROR. Could not locate meta series for $tgt"
	    exit 1
	fi
}

do_init() {
	kgit-meta --init $meta_series
	if [ $? -ne 0 ]; then
	    echo "ERROR initializing git tree, exiting"
	    exit 1
	fi
}

do_apply() {
	kgit-meta -v -v --apply $meta_series
	if [ $? -ne 0 ]; then
	    echo "ERROR. could not update git tree"
	    exit 1
	fi
}

if [ -z "$meta_series" ]; then
    find_meta_series $ktgt
    if [ -z "$meta_series" ]; then
	echo "ERROR. Could not find a meta series for $branch"
	exit 1
    fi
fi

do_init $meta_series
do_apply $meta_series
