#!/usr/bin/env bash
########################################################################
# Copyright 2014 Lukas Bestle <project-projectr@lukasbestle.com>
# License   MIT
########################################################################
# Reverses a deployable project to the last version.
#
# Usage: project_rollback <project>
#        
#        <project>  Path to the project
########################################################################

project="$1"

if [[ -z "$project" ]]; then
	# Print help
	echo -e "\033[1mUsage:\033[0m \033[34mproject_rollback\033[0m <project>"
	exit 1
fi

# Check if the project exists
if [[ ! -f "$project/.project" ]]; then
	echo -e "\033[31mThe project \033[34m$project\033[31m does not exist or is invalid.\033[0m" >&2
	exit 1
fi

# Check if the project is deployable
if [[ ! -f "$project/.origin" ]]; then
	echo -e "\033[31mThe project \033[34m$project\033[31m is not deployable and therefore can't be rolled back.\033[0m" >&2
	exit 1
fi

# Check if the project currently has a last version
if [[ ! -e "$project/last" ]]; then
	echo -e "\033[31mThe project \033[34m$project\033[31m currently does not have a last version.\033[0m" >&2
	echo -e "\033[31mIt has probably already been rolled back since the latest deployment.\033[0m" >&2
	exit 1
fi

echo -e "\033[1mRolling project \033[34m$project\033[0;1m back to last version...\033[0m"
if rm -f "$project/current" && mv "$project/last" "$project/current"; then
	echo -e " => \033[32mSuccess.\033[0m"
else
	echo -e " => \033[31mSomething went wrong.\033[0m" >&2
	exit 1
fi

# Run post-link script if existing
if [[ -x "$project/current/.postlink.sh" ]]; then
	# Set the working directory to the destination
	oldpwd="$(pwd)"
	cd "$project/current"
	
	echo -e "\033[1mRunning post-link script...\033[0m"
	if ! $project/current/.postlink.sh; then
		echo -e " => \033[31mSomething went wrong.\033[0m" >&2
		exit 1
	fi
	echo -e " => \033[32mSuccess.\033[0m"
	
	cd "$oldpwd"
fi
