SET NOCOUNT ON 

DECLARE @ErrorTag NVARCHAR(20) 
SET			@ErrorTag = '###ERROR###'

DECLARE @WarningTag NVARCHAR(20) 
SET			@WarningTag = '###WARNING###'

DECLARE @AdviceTag NVARCHAR(20) 
SET			@AdviceTag = '###ADVICE###'

DECLARE @HeaderTag NVARCHAR(20) 
SET			@HeaderTag = '###HEADER###'

DECLARE @DataTag NVARCHAR(20) 
SET			@DataTag = '###DATA###'

DECLARE @DescTag NVARCHAR(20) 
SET	@DescTag = '###DESCRIPTION###'

DECLARE @colSeperator NVARCHAR(20) 
SET			@colSeperator = ':,:'

DECLARE @ScriptName		NVARCHAR(MAX)
DECLARE @retCode		INT
DECLARE @errorCode		INT
DECLARE @CSOSInfo		NVARCHAR(MAX)
DECLARE @prevReleaseID INT = 0
DECLARE @currentTime BIGINT = 0

SET @ScriptName			= 'CommServe license check: '
SET @retCode			= 0
SET @errorCode			= 0
SET @CSOSInfo 			= ''
SET @currentTime 		= dbo.GetUnixTime(GETUTCDATE())

PRINT @DescTag + ' Check for usage-based licenses (also called Client Access licenses) and expired commserv'

select top 1 @prevReleaseID = id from simAllGalaxyRel order by id desc

IF 2 = ( SELECT COUNT(*) FROM licAAL WHERE simLicAppTypeId in (100019, 100018) )
BEGIN
	SET @retCode = 2

	PRINT  @ErrorTag + ' The CommServe has both [Protected Virtual Machines] and [CPU Sockets on Hypervisor Hosts] licenses, which are mutually exclusive starting from version 11.'
	PRINT  @AdviceTag + ' You must obtain a new license file with only one of the licenses included.'
END
--The check is only needed for release upgrade.
IF @prevReleaseID < 16 AND NOT EXISTS(SELECT id FROM LicUsage 
	WHERE OpType = 'Install' AND ( dbo.GetUnixTime(ExpiryDateUTC) = 0 OR dbo.GetUnixTime(ExpiryDateUTC) > @currentTime )
	AND LicType NOT IN (10,26,71,16777216,33554432,50331648,67108864)) AND EXISTS(SELECT id FROM LicUsage 
	WHERE OpType = 'Install' AND LicType NOT IN (10,26,71,16777216,33554432,50331648,67108864))
BEGIN	
	SET @retCode = 2

	PRINT  @ErrorTag + ' The CommServe is already expired.'
	PRINT  @AdviceTag + ' You must obtain a new license file.'
END

SET	@errorCode = @@ERROR 
IF	@errorCode != 0 GOTO CX_EXIT

CX_EXIT:

IF @errorCode <> 0
BEGIN
	PRINT @ScriptName + 'failed with SQL Error [' + CAST(@errorCode AS VARCHAR(20)) + ']'
	SELECT 2
END
ELSE
BEGIN
	IF @retCode = 0
		PRINT @ScriptName + 'passed'
	SELECT @retCode 
END

RETURN