import groovy.json.JsonSlurper

def cleanSession(boolean rpcodeToo) {
  def s = request.getAuthSession(true)

  if (rpcodeToo) {
	s.removeAttribute('agov.ident.rpcode.backup')
	s.removeAttribute('agov.ident.rpcode')
	s.removeAttribute('agov.ident.entityId')
  }
  def sessionKeySet = new HashSet(session.keySet())
  sessionKeySet.each { key ->
    if ( key ==~ /ch.nevis.auth.saml..*/ ) {
	  LOG.debug("Deleted session attribute '${key}'")
	  s.removeAttribute(key)
	}
  }
}

// for auditing
def sourceIp = request.getLoginContext()['connection.HttpHeader.X-Real-IP'] ?: 'unknown'
def userAgent = request.getLoginContext()['connection.HttpHeader.user-agent'] ?: request.getLoginContext()['connection.HttpHeader.User-Agent'] ?: 'unknown'
def referer = request.getLoginContext()['connection.HttpHeader.referer'] ?: request.getLoginContext()['connection.HttpHeader' +
		'.Referer'] ?: '-'
def origin = request.getLoginContext()['connection.HttpHeader.origin'] ?: request.getLoginContext()['connection.HttpHeader' +
		'.Origin'] ?: '-'

// 0) clean up, if we have a SAML Response in session
if (session['ch.nevis.auth.saml.response.id']) {
  // keep rpcode in session, if retrying after SAML error
  def keepRpcode = session['ch.nevis.auth.saml.response.statusCode'] == 'urn:oasis:names:tc:SAML:2.0:status:Responder'
  cleanSession(!keepRpcode)
}

// 1) we need to know the code of the RP
def rpcode = inargs['rpcode'] ?: inargs['RelayState'] ?: session['agov.ident.rpcode']
def rpcodeBackup = session['agov.ident.rpcode']
def rpentity = '-'

if (rpcode)
{
  if (rpcodeBackup) {
    response.setSessionAttribute('agov.ident.rpcode.backup', rpcodeBackup)
  }
  response.setSessionAttribute('agov.ident.rpcode', rpcode)
} else {
  cleanSession(true)
  LOG.info("Event='IDENT-INVALIDREQ', rpcode='missing', SourceIp=${sourceIp}, UserAgent='${userAgent}', Referer='${referer}', Origin='${origin}'")
  response.setResult('inavlidurl')
  return
}

// 2) load rp settings in session (if needed)
if (rpcode != rpcodeBackup) {
  def slurper = new JsonSlurper()
  def rpMap = slurper.parseText(parameters['rpcode.list'])
  LOG.debug(">>> rpMaP: ${rpMap}")
  if (!rpMap[rpcode]) {
	  cleanSession(true)
	  LOG.info("Event='IDENT-INVALIDREQ', rpcode='${rpcode}', SourceIp=${sourceIp}, UserAgent='${userAgent}', Referer='${referer}', Origin='${origin}'")
	  response.setResult('inavlidurl')
	  return
  }
  rpentity=rpMap[rpcode]
  response.setSessionAttribute('agov.ident.entityId', rpMap[rpcode])
}

// 3) if we have a response ...
if (inargs['SAMLResponse']) {
    response.setResult('processResponse')
    return
}

// 4) otherwise
LOG.info("Event='IDENT-INITREQ', rpcode='${rpcode}', rpentity='${rpentity}', SourceIp=${sourceIp}, UserAgent='${userAgent}', Referer='${referer}', " +
		"Origin='${origin}'")
response.setResult('sendAuthnRequest')
return

