#!/bin/sh

# Extract a snapshot zipfile

#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 2 of the License, or
#  (at your option) any later version.
#
#  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.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Usage: import PATH_TO_ZIPFILE
#
# Example:
#
#   ../git-tools/import ../path/to/OCT612xAPI-01.03.05.zip
#
# Zip files should be a standard release ones. We assume the name begins
# with "OCT612xAPI-". The date of the commit is the date of the ReleaseNotes
# file.

set -e

AUTHOR="Octasic Inc. <support@octasic.com>"
PREFIX="OCT612x-"
top_dir="../tmp"
new_dir="$top_dir/new"

# make sure source files are text. Hmm... any better way?
convert_cr_lf() {
	find * -name '*.[ch]' | xargs sed -i -e 's/\r$//'
}

extract() {
	zipfile="$1"

	if [ ! -f "$zipfile" ]; then
		echo >&2 "Error: $zipfile is not a file. Should be zipfile. Aborting"
		exit 1
	fi

	rm -rf "$new_dir"
	mkdir "$new_dir"

	(cd "$new_dir" && unzip -q -a "../$zipfile")
	(cd "$new_dir" && convert_cr_lf)

	sub_dir=`echo "$new_dir"/*`
	sub_dir_name=`basename $sub_dir`
	ver=${sub_dir_name#$PREFIX}
	zip_name=`basename "$zipfile"`
	#date=${zip_name#$PREFIX}
	#date=${date%.tar.gz}
	target_dir="$top_dir/$PREFIX$ver"
	rm -rf "$target_dir"
	mv "$sub_dir" "$target_dir"
	rmdir "$new_dir"
}

abort() {
	me=`basename $0`
	echo >&2 "$me: Error: $1"
	exit 1
}

import() {
	me=`basename $0`
	if [ ! -d .git ]; then
		abort "Must be run from the base of the git repository"
		exit 1
	fi

	src_dir="$1"
	if [ ! -d "$src_dir" ]; then
		abort "First parameter must be the source directory"
	fi
	base=`basename $src_dir`
	ver=${base#$PREFIX}

	commit_msg="importing $base"
	tag="v$ver"

	#echo "commit_msg: <$commit_msg>"
	#echo "tag: <$tag>"
	#exit 0

	rm -rf *		# Does not remove .git
	cp -a "$src_dir"/* .
	git add *
	# If some files were gone, tell git about it. Chances are half of them
	# are renames.
	if git status | grep -q 'deleted:'; then
		git status | awk '/deleted:/{print $3}' | xargs git rm
	fi
	git_date=`date -R -r "$src_dir/ReleaseNotes.txt"`
	git commit --author "$AUTHOR" --date "$git_date"  -m  "$commit_msg"
	if [ "$tag" != '' ]; then
		git tag "$tag"
	fi
}

extract "$@"
import "$target_dir" # $target_dir is set in 'extract'
