SET NOCOUNT ON 

DECLARE @ErrorTag	NVARCHAR(20) = '###ERROR###'
DECLARE @WarningTag	NVARCHAR(20) = '###WARNING###'
DECLARE @AdviceTag	NVARCHAR(20) = '###ADVICE###'
DECLARE @DescTag 	NVARCHAR(20) = '###DESCRIPTION###'
DECLARE @errorCode	INT = 0
DECLARE @appType	INT
DECLARE @PkgName 	NVARCHAR(256) = 'Exchange Public Folder'
DECLARE @LicName 	NVARCHAR(256) = 'Application Class 1'
DECLARE @FreePermLicensesAvailable INT = 0
DECLARE @FreeEvalLicensesAvailable INT = 0
DECLARE @TotalLicensesUsed INT

SET @appType = (SELECT type FROM APP_iDAType WHERE name = @PkgName)

SET @TotalLicensesUsed = (SELECT COUNT(distinct clientId) 
FROM   APP_IDAName A WITH (NOLOCK) LEFT OUTER JOIN LicUsage L ON A.appTypeId = L.AppType AND A.clientId = L.CId
WHERE  appTypeId = @appType AND status&(2+4) = 0 AND L.AppType IS NULL)

PRINT @DescTag + ' Check for '+@LicName+' Licenses for ' + @PkgName

IF (@TotalLicensesUsed = 0)
BEGIN
	SET @errorCode = 0
	GOTO CX_EXIT
END

DECLARE @retLicData	TABLE (	licName	varchar(1024),
				TotalPermLicensesIssued INTEGER,
				FreePermLicensesAvailable INTEGER,
				TotalEvalLicensesIssued INTEGER,
				FreeEvalLicensesAvailable INTEGER	)
				
INSERT INTO @retLicData
exec QS_GetLicenseInfo @LicName
	
SELECT @FreePermLicensesAvailable = FreePermLicensesAvailable , @FreeEvalLicensesAvailable = FreeEvalLicensesAvailable FROM @retLicData

/*CS has sufficient quantity*/
IF (@FreePermLicensesAvailable < 0) OR (@FreePermLicensesAvailable >= @TotalLicensesUsed)
BEGIN
	SET @errorCode = 0
	GOTO CX_EXIT
END

IF ( @FreePermLicensesAvailable + @FreeEvalLicensesAvailable >= @TotalLicensesUsed)  OR (@FreeEvalLicensesAvailable < 0)
BEGIN
	SET @errorCode = 1
	GOTO CX_EXIT
END
ELSE
BEGIN
	SET @errorCode = 2
	GOTO CX_EXIT
END

CX_EXIT:
BEGIN
	IF @errorCode = 2
	BEGIN
		PRINT  @ErrorTag + ' The CommServe does not have sufficient '+@LicName+' licenses for clients that have the '+@PkgName+' agent.'
		PRINT  @AdviceTag + ' Contact your Software Provider to obtain the necessary licenses'
	END
	ELSE if @errorCode = 1	
	BEGIN
		PRINT  @WarningTag + cast( (@TotalLicensesUsed - @FreePermLicensesAvailable) as varchar(10) ) + ' Permanent licenses will be converted to Evaluation licenses (which expire in 60 days)'
		PRINT  @AdviceTag + ' Make sure that the CommServe has the necessary permanent '+@LicName+' licenses'
	END
END

SELECT @errorCode
