def redirect(location) {
    outargs.put('nevis.transfer.type', 'redirect')
    outargs.put('nevis.transfer.destination', location)
}

def getReturnURL() {
    if (inargs.containsKey('return')) {
        return inargs.get('return')
    }
    // determine returnURL based on Referer header (if present and not pointing to this page)
    def referer = request.getHttpHeader('Referer')
    if (referer == null) {
        LOG.debug('no Referer header found')
        return null
    }
    // strip query String for comparison
    String previous = referer.contains('?') ? referer.substring(0, referer.indexOf("?")) : referer
    def current = request.getCurrentResource()
    if (current.startsWith(previous)) {
        LOG.debug("Referer header $referer cannot be used as return URL - cyclic redirect")
        return null
    }
    return referer
}

if (inargs.containsKey('logout-confirm')) {
    def current = request.getCurrentResource()
    // user has confirmed logout -> replace /logout with /?logout
    String location
    if (current.contains('?')) {
        location = current.replace("/logout?", "/?logout&")
    }
    else {
        location = current.replace("/logout", "/?logout")
    }
    redirect(location)
    return
}

if (inargs.containsKey('logout-abort')) {
    // user has aborted logout -> redirect to stored return URL
    def location = session.get('logout-abort-url')
    redirect(location)
    return
}

// user has not clicked any button -> render GUI
response.setGuiName('saml_logout_confirm')
response.setGuiLabel('title.logout.confirmation')
// not setting a target as the API has been removed
response.addInfoGuiField('info', 'info.logout.confirmation', null)
response.addButtonGuiField('logout-confirm', 'continue.button.label', 'true')

def returnURL = getReturnURL()

if (returnURL != null) {
    // store return URL in session
    session.put('logout-abort-url', returnURL)
}

if (session.containsKey('logout-abort-url')) {
    // add cancel button to go back
    response.addButtonGuiField('logout-abort', 'cancel.button.label', 'true')
}