<?php
if (isset($_SERVER['REMOTE_USER'])) {
    include("/opt/secioss/var/www/lib/shib_sp.php");
} else {
    include("/opt/secioss/var/www/lib/saml_sp.php");
}

$logid = 'AutoLogin';

require_once("../lib/util.php");

if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
    $log = &Log::singleton('syslog', LOG_LOCAL5, $logid);
} else {
    $opts = array('locking' => true, 'timeFormat' => '%Y/%m/%d %H:%M:%S');
    $log = &Log::singleton('file', '/opt/secioss/var/log/auth.log', $logid, $opts);
}

$conf = parse_ini_file("../conf/config.ini", true);
if (empty($conf)) {
    $log->crit(logformat("Can't read config.ini"));
    exit(1);
}

$name = '';
if (isset($_GET['sso_app'])) {
    $name = $_GET['sso_app'];
}
if (!$name && preg_match('/^(.*).php$/', basename($_SERVER['SCRIPT_FILENAME']), $match)) {
    $name = $match[1];
}

if (!$name || !file_exists("../conf/$name.ini")) {
     $log->err(logformat("Invalid application name($name)"));
     exit(1);
}

$appconf = parse_ini_file("../conf/$name.ini", true);
if (empty($appconf)) {
     $log->err(logformat("Can't read $name.ini"));
     exit(1);
}

if (!isset($conf['autologin'])) {
     $log->err(logformat("Set autologin configuration"));
     exit(1);
}

if (isset($appconf['autologin'])) {
    foreach ($appconf['autologin'] as $key => $value) {
        $conf['autologin'][$key] = $value;
    }
}

foreach ($_GET as $key => $value) {
    $appconf['url'][$key] = $value;
}

$username = isset($appconf['postName']['username']) ? $appconf['postName']['username'] : null;
$password = isset($appconf['postName']['password']) ? $appconf['postName']['password']: null;
$postData = isset($appconf['postData']) ? $appconf['postData'] : null;
$cookie = isset($appconf['cookie']) ? $appconf['cookie'] : null;
$content = isset($appconf['content']) ? $appconf['content'] : null;
$app = isset($conf['apps']) && isset($conf['apps'][$name]) && $name != 'accessmanager' ? $name : null;
$debug = isset($conf['autologin']['debug']) ? $conf['autologin']['debug'] : null;

$login = new AutoLogin($conf['autologin']['storage'], $conf['autologin'],
        $app, $appconf['url'], $username, $password,
        $postData, $cookie, $content, $debug);

$user = isset($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'] : null;
$user = preg_replace('/^[^\\\\]+\\\\/', '', $user);
$rc = $login->setUser($user);
if (PEAR::isError($rc)) {
     $log->crit(logformat("Getting user data failed: ". $rc->getMessage()));
     exit(1);
}

$rc = $login->start();
if (PEAR::isError($rc)) {
     $log->crit(logformat("Auto login to $name failed: ". $rc->getMessage()));
} else {
     $log->notice(logformat("Auto login to $name succeeded"));
}
?>
