#!/bin/bash
set -e
set -u

######################
## VARIABLES
######################

ARTIFACTS_LOCAL_MODE=false
CHECK_IF_NEWER_VERSION=true

TMP_DIR="/tmp"
USER_HOME=$( getent passwd "$USER" | cut -d: -f6 )
SMARTKIT_DIR="$USER_HOME/smartkit"
SMARTKIT_REPO_DIR="$SMARTKIT_DIR/repository"
SMARTKIT_BACKUP_DIR="$SMARTKIT_DIR/backup"
SMARTKIT_COMMONS_DIR="$SMARTKIT_DIR/smartkit-commons"
SMARTKIT_PRINTING_SERVICE_DIR="$SMARTKIT_DIR/smartkit-printing-service"

SMEUP_REPO="https://repo.smeup.cloud/nexus/content/repositories" 
GROUP_ID="com.smeup.smartkit"
GROUP_ID_URL="${GROUP_ID//.//}"
SMARTKIT_ARTIFACT_POSTFIX="full.zip"
SMARTKIT_ARTIFACT_ID="smartkit-printing-service"

SMARTKIT_PRINTING_SERVICE_POD_PORTBASE=1000

PRN_SVC_TEMPLATE_PATH="src/templates/sps"
DOWNLOAD_URL="https://repo.smeup.cloud/nexus/repository/releases/com/smeup/rdsv6-wcm/1.0.0/rdsv6-wcm-1.0.0.war"

PRN_SVC_PREFIX="sps"
PRN_SVC_ID=undefined
PRN_SVC_NAME=undefined
PRN_SVC_PORTBASE=undefined

######################
## FUNCTIONS
######################

## set $1=$2 in $file. If $1 is missing and $4 setting before it, else setting at the end of the file
function set_variable () {
	if ! grep -R "^[#]*\s*$1=.*" $3 > /dev/null; then
		if (( $# == 4 )); then
	  		sed -ir "/^[#]*\s*$4.*/i $1=$2" $3		
		else 
			echo "$1=$2" >> $3
		fi
	else
		sed -ir "s|^[#]*\s*$1=.*|$1=$2|" $3
	fi
}

function find_last_release_version() {
	if [ "$ARTIFACTS_LOCAL_MODE" = true ] ; then
		cd $SMARTKIT_REPO_DIR
		LAST_RELEASE_VERSION=$(ls $SMARTKIT_ARTIFACT_ID-*$SMARTKIT_ARTIFACT_POSTFIX | tail -n 1) 
		LAST_RELEASE_VERSION=$(echo "$LAST_RELEASE_VERSION" | sed "s/-$SMARTKIT_ARTIFACT_POSTFIX//")
		LAST_RELEASE_VERSION=$(echo "$LAST_RELEASE_VERSION" | sed "s/$SMARTKIT_ARTIFACT_ID-//")
		echo -e "[ARTIFACTS_LOCAL_MODE=true]: found $SMARTKIT_ARTIFACT_ID last release version in $SMARTKIT_REPO_DIR: \c"
	else
		REPO="releases"
		LAST_RELEASE_VERSION=$(xmllint --xpath "string(//release)" <(wget -O - "${SMEUP_REPO}/${REPO}/${GROUP_ID_URL}/${SMARTKIT_ARTIFACT_ID}/maven-metadata.xml"))
		echo -e "Found $SMARTKIT_ARTIFACT_ID last release version in $SMEUP_REPO: \c"
	fi
	if [ -z "$LAST_RELEASE_VERSION" ] ; then
		echo -e "\033[31m$SMARTKIT_ARTIFACT_ID last release version not found!!!\033[0m"
		exit 1
	else
		echo $LAST_RELEASE_VERSION
	fi
}

function find_release_versions() {
	if [ "$ARTIFACTS_LOCAL_MODE" = true ] ; then
		cd $SMARTKIT_REPO_DIR
		RELEASE_VERSIONS=$(ls $SMARTKIT_ARTIFACT_ID-*$SMARTKIT_ARTIFACT_POSTFIX)  
		RELEASE_VERSIONS=$(echo "$RELEASE_VERSIONS" | sed "s/-$SMARTKIT_ARTIFACT_POSTFIX//")
		RELEASE_VERSIONS=$(echo "$RELEASE_VERSIONS" | sed "s/$SMARTKIT_ARTIFACT_ID-//")
		echo "[ARTIFACTS_LOCAL_MODE=true]: found $SMARTKIT_ARTIFACT_ID release versions in $SMARTKIT_REPO_DIR:"
	else
		REPO="releases"
		RELEASE_VERSIONS=$(xmllint --xpath "string(//versions)" <(wget -O - "${SMEUP_REPO}/${REPO}/${GROUP_ID_URL}/${SMARTKIT_ARTIFACT_ID}/maven-metadata.xml"))
		echo "Found $SMARTKIT_ARTIFACT_ID release versions in $SMEUP_REPO:"
	fi
	if [ -z "$RELEASE_VERSIONS" ] ; then
		echo -e "\033[31m$SMARTKIT_ARTIFACT_ID release versions not found!!!\033[0m"
		exit 1
	else
		echo $RELEASE_VERSIONS
	fi
}

function check_if_newer_version() {
	find_last_release_version
	find_local_version
	if [ "$LAST_RELEASE_VERSION" \> "$SMARTIT_WEBUP_LOCAL_VERSION" ] ; then
		echo -e "\033[0;33mThere is a newer smartkit-printing-service version. Updating is suggested!\033[0m"		
		echo -e "\033[0;33mIf you want to update terminate with CTRL-C and follow update instructions in $SMARTKIT_PRINTING_SERVICE_DIR/docs/use.md\033[0m"		
		read  -n 1 -p "If instead you want to continue press return..." go
	else
		echo "smartkit-printing-service is at last available version."
	fi
}

function download_version {
	if [ "$ARTIFACTS_LOCAL_MODE" = false ] ; then
		echo "Downloading $SMARTKIT_ARTIFACT_ID-$VERSION-full.zip from web and put it in $SMARTKIT_REPO_DIR"
		if [[ $VERSION == *"SNAPSHOT"* ]]; then
			REPO="snapshots"
			VERSIONEDFILE=$(xmllint --xpath "string(//value)" <(wget -O - "${SMEUP_REPO}/${REPO}/${GROUP_ID_URL}/${SMARTKIT_ARTIFACT_ID}/${VERSION}/maven-metadata.xml"))
		else
		    REPO="releases"
		    VERSIONEDFILE=$VERSION
		fi	
		FILENAME="${SMARTKIT_ARTIFACT_ID}-${VERSIONEDFILE}-${SMARTKIT_ARTIFACT_POSTFIX}"
		LOCAL_FILENAME="${SMARTKIT_ARTIFACT_ID}-${VERSION}-${SMARTKIT_ARTIFACT_POSTFIX}"
		URL="${SMEUP_REPO}/${REPO}/$GROUP_ID_URL/${SMARTKIT_ARTIFACT_ID}/$VERSION/$FILENAME"
		echo $URL
		rm -fr $SMARTKIT_REPO_DIR/$LOCAL_FILENAME		
		wget $URL -O $SMARTKIT_REPO_DIR/$LOCAL_FILENAME			
	fi
}

function unzip_version_in_tmp {
	echo "Unzip $SMARTKIT_ARTIFACT_ID-$VERSION-full.zip in $TMP_DIR"
	cp -R $SMARTKIT_REPO_DIR/$SMARTKIT_ARTIFACT_ID-$VERSION-full.zip $TMP_DIR
	cd $TMP_DIR
	rm -fr $SMARTKIT_ARTIFACT_ID-$VERSION
	unzip -q $SMARTKIT_ARTIFACT_ID-$VERSION-full.zip	
}

## NB: docker images names cannot be uppercase
function read_prn_svc_id() {
	PRN_SVC_ID=$1
	PRN_SVC_NAME=$PRN_SVC_PREFIX-$PRN_SVC_ID
	if ! [[ "$PRN_SVC_ID" =~ ^[0-9a-z]+$ ]]; then
		echo -e "\033[31msps id $PRN_SVC_ID is incorrect. Choose lower case chars or numbers\033[0m"
		exit 1	
	fi
	PRN_SVC_ID_LEN=${#PRN_SVC_ID}
	if [[ $PRN_SVC_ID_LEN -ge 7 ]]; then
		echo -e "\033[31msps id $PRN_SVC_ID is incorrect. Max length is 6\033[0m"
		exit 1	
	fi	
}

function calculate_prn_svc_port_base() {
	cd $SMARTKIT_PRINTING_SERVICE_DIR
	PRN_SVC_PORTBASE=`ls | grep $PRN_SVC_PREFIX | wc -l`
	PRN_SVC_PORTBASE=`expr $PRN_SVC_PORTBASE \* $SMARTKIT_PRINTING_SERVICE_POD_PORTBASE`    
	echo "sps portbase: $PRN_SVC_PORTBASE"
}

function calculate_prn_svc_dir() {
	PRN_SVC_DIR=$SMARTKIT_PRINTING_SERVICE_DIR/$PRN_SVC_NAME
}

function find_prn_svc_local_version(){
	PRN_SVC_LOCAL_VERSION=""
	if [ -d "$PRN_SVC_DIR" ]; then
       	cd $PRN_SVC_DIR
       	PRN_SVC_LOCAL_VERSION="`cat version.info`"
    fi
    echo "Found sps local version: $PRN_SVC_LOCAL_VERSION"	
}

function find_local_version(){
	cd $SMARTKIT_PRINTING_SERVICE_DIR
    SMARTIT_WEBUP_LOCAL_VERSION="`cat version.info`"
    echo "Found smartkit smeup printing service local version: $SMARTIT_WEBUP_LOCAL_VERSION"	
}

function smartkit_printing_service_detail() {
	find_local_version   
}

function smartkit_printing_service_releases() {
	find_release_versions
	echo "Releases details can be found here: $SMARTKIT_PRINTING_SERVICE_DIR/docs/releases.md. If they aren't updated, update smartkit-printing-service following instructions in $SMARTKIT_PRINTING_SERVICE_DIR/docs/use.md". 
}

function create_files() {
	## copy all template dir
	cp -R $TMP_DIR/$SMARTKIT_ARTIFACT_ID-$VERSION/$PRN_SVC_TEMPLATE_PATH $PRN_SVC_DIR
	## set version.info 
	cp -R $TMP_DIR/$SMARTKIT_ARTIFACT_ID-$VERSION/version.info $PRN_SVC_DIR		
	cd $PRN_SVC_DIR
	find . -name "*.sh" -exec chmod +x {} \;
}

function update_files() {
	## remove old script files (removed also terraform.tfstate and terraform tmp files because destroy called and was ok...)
	sudo rm -fr $PRN_SVC_DIR/scripts
	## copy new scripts files
	sudo cp -R $TMP_DIR/$SMARTKIT_ARTIFACT_ID-$VERSION/$PRN_SVC_TEMPLATE_PATH/scripts $PRN_SVC_DIR
	## override version.info 
	sudo rm -fr $PRN_SVC_DIR/version.info
	sudo cp -R $TMP_DIR/$SMARTKIT_ARTIFACT_ID-$VERSION/version.info $PRN_SVC_DIR
	cd $PRN_SVC_DIR
	sudo find . -name "*.sh" -exec chmod +x {} \;
}

function prn_svc_list() {
	echo "Searching spss into $SMARTKIT_PRINTING_SERVICE_DIR..."
	PRN_SVC_LIST=$(sudo find $SMARTKIT_PRINTING_SERVICE_DIR  -type d -iname "$PRN_SVC_PREFIX*" -printf "%f\n") 
	if [ -z "$PRN_SVC_LIST" ] ; then
		echo "No sps found"
	else 
		PRN_SVC_LIST=$(echo "$PRN_SVC_LIST" | sed "s/$PRN_SVC_PREFIX-//")
		echo $PRN_SVC_LIST
	fi
}

function prn_svc_detail() {
	calculate_prn_svc_dir
	find_prn_svc_local_version	
	echo PRN_SVC_NAME $PRN_SVC_NAME
	$PRN_SVC_DIR/scripts/service.sh status $PRN_SVC_NAME
}

function prn_svc_stop() {
	calculate_prn_svc_dir	
	$PRN_SVC_DIR/scripts/service.sh stop $PRN_SVC_NAME
}

function prn_svc_start() {
	calculate_prn_svc_dir	
	$PRN_SVC_DIR/scripts/service.sh start $PRN_SVC_NAME
}

function prn_svc_config() {
	$PRN_SVC_DIR/scripts/config.sh
}

function prn_svc_apply() {
	$PRN_SVC_DIR/scripts/apply.sh
}

function prn_svc_destroy() {
	echo -e "\033[0;33mStart destroying of sps with id $PRN_SVC_ID\033[0m"
	read  -n 1 -p "Press return to continue..." go
	calculate_prn_svc_dir
	find_prn_svc_local_version
	if [ -z "$PRN_SVC_LOCAL_VERSION" ] ; then
		echo -e "\033[31msps with id $PRN_SVC_ID doesn't exists.\033[0m"
		exit 1
	else
		$PRN_SVC_DIR/scripts/uninstall.sh $SMARTKIT_PRINTING_SERVICE_DIR $PRN_SVC_NAME
	fi	
}

function prn_svc_remove() {
	prn_svc_destroy
	sudo rm -fr $PRN_SVC_DIR
}

function prn_svc_backup() {
	echo "Backup sps with id $PRN_SVC_ID"
	calculate_prn_svc_dir
	BACKUP_ID=$(date +%s)
	sudo cp -Rp $PRN_SVC_DIR $SMARTKIT_BACKUP_DIR/$PRN_SVC_NAME-$BACKUP_ID
	echo "Backupped $PRN_SVC_ID into $SMARTKIT_BACKUP_DIR/$PRN_SVC_ID-$BACKUP_ID"
}

function prn_svc_restore() {
	echo "Restore sps with id $PRN_SVC_ID and backup id $BACKUP_ID"
	calculate_prn_svc_dir
	find_prn_svc_local_version
	if [ ! -z "$PRN_SVC_LOCAL_VERSION" ] ; then
		echo -e "\033[31msps with id $PRN_SVC_ID exists. You have to remove $PRN_SVC_ID if you want to restore.\033[0m"
		exit 1
	fi	
	sudo cp -R $SMARTKIT_BACKUP_DIR/$PRN_SVC_NAME-$BACKUP_ID $PRN_SVC_DIR 	
	$PRN_SVC_DIR/scripts/install.sh $SMARTKIT_PRINTING_SERVICE_DIR $PRN_SVC_NAME
}

function prn_svc_create() {
	if [ -z "$VERSION" ] ; then
		find_last_release_version
		VERSION=$LAST_RELEASE_VERSION
	fi

	#echo "PRN_SVC_ID" $PRN_SVC_ID
	#echo "PRN_SVC_NAME" $PRN_SVC_NAME
	
	calculate_prn_svc_dir
	find_prn_svc_local_version
		
	if [ -z "$PRN_SVC_LOCAL_VERSION" ] ; then
		
		echo "Create new sps with id $PRN_SVC_ID at version $VERSION"
		read  -n 1 -p "Press return when read..." go
		
		download_version
		unzip_version_in_tmp
		
		create_files

		$PRN_SVC_DIR/scripts/install.sh $SMARTKIT_PRINTING_SERVICE_DIR $PRN_SVC_NAME
				
		
	else 
		echo -e "\033[31msps with id $PRN_SVC_ID already exists! Remove it or update it! \033[0m"
		exit 1	
	fi

}

function prn_svc_update() {
	if [ -z "$VERSION" ] ; then
		find_last_release_version
		VERSION=$LAST_RELEASE_VERSION
	fi
	
	calculate_prn_svc_dir
	find_prn_svc_local_version
	
	if [ -z "$PRN_SVC_LOCAL_VERSION" ] ; then
		echo -e "\033[31msps with id $PRN_SVC_ID doesn't exists! You must create it!\033[0m"
		exit 1
	else
		echo "Update sps with id $PRN_SVC_ID from version $PRN_SVC_LOCAL_VERSION to version $VERSION and install latest version of application"
		read  -n 1 -p "Press return to continue..." go
		
		download_version
		unzip_version_in_tmp
		read  -n 1 -p "Press return to continue..." go
						
		prn_svc_backup
		read  -n 1 -p "Press return to continue..." go
		
		echo -e "\033[0;33mNOTE: To update a sps it will be destroyed and be rebuilt as new. State files won't be destroyed (ex: params, converted spool...).\033[0m"		
		read  -n 1 -p "Press return to continue..." go
		
        update_files								
		$PRN_SVC_DIR/scripts/install.sh $SMARTKIT_PRINTING_SERVICE_DIR $PRN_SVC_NAME

	fi

}

function prn_svc_rebuild() {
	if [ -z "$VERSION" ] ; then
		find_last_release_version
		VERSION=$LAST_RELEASE_VERSION
	fi
	
	calculate_prn_svc_dir
	find_prn_svc_local_version
	
	if [ -z "$PRN_SVC_LOCAL_VERSION" ] ; then
		echo -e "\033[31msps with id $PRN_SVC_ID doesn't exists! You must create it!\033[0m"
		exit 1
	else
		echo "Rebuild sps infrastrucure with id $PRN_SVC_ID and install latest version of application"
		read  -n 1 -p "Press return to continue..." go

		$PRN_SVC_DIR/scripts/install.sh $SMARTKIT_PRINTING_SERVICE_DIR $PRN_SVC_NAME
	fi

}



##------------------------------------------------------------------
## Main
##------------------------------------------------------------------

echo "Main script of smartkit-printing-service..."

if [ "$CHECK_IF_NEWER_VERSION" = true ] ; then
	check_if_newer_version
fi

if [ $# -lt 1 ]

then
	echo "Call with -h or --help"
	exit 0

else
  
	if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
		echo "Usage:"
		echo " `basename "$0"` detail -> show details about your installed smartkit-printing-service"	
		echo " `basename "$0"` releases -> show smartkit-printing-service/sps available releases"	
		echo " `basename "$0"` sps-list -> get the list of your sps services" 
		echo " `basename "$0"` sps-create [ID] -> creates a sps with id [ID]."
		echo " `basename "$0"` sps-update [ID] -> updates a sps with id [ID]. It backups and destroys the old one (leave state files and other resources)."
		echo " `basename "$0"` sps-rebuild [ID] -> rebuild infrastructure of sps with id [ID]. It's required if you change some terraform variable file (leave state files and other resources)."
		echo " `basename "$0"` sps-detail [ID] -> show details about sps with id [ID]"
		echo " `basename "$0"` sps-stop [ID] -> stop a sps with id [ID]"
		echo " `basename "$0"` sps-start [ID] -> start a sps with id [ID]"
		echo " `basename "$0"` sps-backup [ID] -> backup a sps with id [ID]"
		echo " `basename "$0"` sps-destroy [ID] -> destroy a sps with id [ID] (leave state files as env and container files)"
		echo " `basename "$0"` sps-remove [ID] -> destroy and remove all what concerns a sps with id [ID]"	
		echo " `basename "$0"` sps-restore [ID] [BACKUPID] -> restore a backupped sps with id '[ID]' and backup id [BACKUPID]"
		echo "Note 1: [ID] must be a max 6 lower case chars or numbers, ex: prod1, test22, etc.."
		echo "Note 2: For more info read $SMARTKIT_PRINTING_SERVICE_DIR/docs/use.md"
		exit 0
	fi  
  
	echo "Command: $1"
	
	if [ "$1" == "detail" ]; then
		smartkit_printing_service_detail			
	elif [ "$1" == "releases" ]; then
		smartkit_printing_service_releases		
	elif [ "$1" == "sps-list" ]; then		
		prn_svc_list	
	elif [ "$1" == "sps-create" ]; then
		read_prn_svc_id $2
		if [ $# -eq 3 ]; then
			VERSION=$3
		else
			VERSION=""
		fi
		echo "Id: $PRN_SVC_ID"
		echo "Version: $VERSION"
		prn_svc_create
	elif [ "$1" == "sps-update" ]; then
		read_prn_svc_id $2
		if [ $# -eq 3 ]; then
			VERSION=$3
		else
			VERSION=""
		fi
		echo "Id: $PRN_SVC_ID"
		echo "Version: $VERSION"
		prn_svc_update	
	elif [ "$1" == "sps-rebuild" ]; then
		read_prn_svc_id $2
		if [ $# -eq 3 ]; then
			VERSION=$3
		else
			VERSION=""
		fi
		echo "Id: $PRN_SVC_ID"
		echo "Version: $VERSION"
		prn_svc_rebuild	
	elif [ "$1" == "sps-detail" ]; then
		read_prn_svc_id $2
		echo "Id: $PRN_SVC_ID"
		prn_svc_detail		
	elif [ "$1" == "sps-stop" ]; then
		read_prn_svc_id $2
		echo "Id: $PRN_SVC_ID"
		prn_svc_stop	
	elif [ "$1" == "sps-start" ]; then
		read_prn_svc_id $2
		echo "Id: $PRN_SVC_ID"
		prn_svc_start			
	elif [ "$1" == "sps-backup" ]; then
		read_prn_svc_id $2
		echo "Id: $PRN_SVC_ID"
		prn_svc_backup				
	elif [ "$1" == "sps-destroy" ]; then
		read_prn_svc_id $2
		echo "Id: $PRN_SVC_ID"
		prn_svc_destroy	
	elif [ "$1" == "sps-remove" ]; then
		read_prn_svc_id $2
		echo "Id: $PRN_SVC_ID"
		prn_svc_remove			
	elif [ "$1" == "sps-restore" ]; then
		read_prn_svc_id $2
		if [ $# -eq 3 ]; then
			BACKUP_ID=$3
		else
			BACKUP_ID=""
		fi		
		prn_svc_restore
	else
		echo "not implemented command"
	fi

fi




