#!/bin/sh
#
# FreeBSD Port Tools 1.11
#
# Copyright (c) 2003-2009, Sergei Kolobov
# Copyright (c) 2013-2014, Mathieu Arnold
# Copyright (c) 2014, Johannes Meixner
# Copyright (c) 2014-2015, Steven Kreuzer
# 
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# cmd_upgrade
# Module for port(1)
# SUMMARY: upgrade a port

# Check if this script is run via port(1)
if [ "${PORTTOOLS}" = "" ]
then
	echo "This script should be run via port(1) front-end"
	exit 1
fi

# Usage
usage ()
{
cat << EOF
FreeBSD Port Tools 1.11
Usage:	port upgrade [-h] [port flags ...]
	-h	- Display this usage summary
	-p	- Create package
EOF
}

# Initialize defaults
PACKAGE="no"

# Parse command line arguments
ARGS=`/usr/bin/getopt hp $*`
if [ $? != 0 ]
then
	echo "Error: invalid arguments"
	usage
	exit 2
fi

set -- $ARGS
while [ x"$1" != x"--" -a x"$1" != x"" ]
do
	i=$1
	case "$i" in
	# help
	-h)
		usage
		exit 0
		;;
	# package
	-p)
		PACKAGE="yes"
		;;
	# end of options
	--)
		shift
		break
		;;
	esac
	shift
done

# Save port flags passed via command line
PORT_FLAGS="$*"
echo "===> flags: ${PORT_FLAGS}"

# See if sudo(1) is needed
SUDO=""
[ `/usr/bin/id -u` = 0 ] || SUDO="sudo"

# Clean work directory first
make clean ${PORT_FLAGS} || exit 1

# Make sure we have correct distfiles
make checksum ${PORT_FLAGS} || exit 1

# Build port
make ${PORT_FLAGS} || exit 1

# Deinstall previous version of port
${SUDO} make deinstall ${PORT_FLAGS} || exit 1

# Install current version of port
${SUDO} make install ${PORT_FLAGS} || exit 1

# Package port if requested
if [ "${PACKAGE}" = "yes" ]
then
	${SUDO} make package FORCE_PACKAGE=yes ${PORT_FLAGS} || exit 1
fi

# Clean work directory
${SUDO} make clean ${PORT_FLAGS} || exit 1

exit 0
