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

$conf = parse_ini_file("../conf/config.ini", true);
if (empty($conf)) {
    print("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")) {
     print("Invalid application name($name)");
     exit(1);
}

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

if (!isset($conf['autologin'])) {
     print("Set autologin configuration");
     exit(1);
}

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

if (isset($conf['autologin']['privatekey'])) {
    $conf['autologin']['publickey'] = preg_replace('/PrivateKey.pem$/', 'PublicKey.pem', $conf['autologin']['privatekey']);
}

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);
$storage = $login->storage;

$user = isset($_GET['user']) ? $_GET['user'] : null;
$user = preg_replace('/^[^\\\\]+\\\\/', '', $user);
$_SERVER['REMOTE_USER'] = $user;
$_SERVER['REMOTE_USER_DATA'] = $storage->options['encryptpwdattr'].'='.$storage->encrypt(isset($_GET['pass']) ? $_GET['pass'] : null);
$rc = $login->setUser($user);
if (PEAR::isError($rc)) {
     print("Getting user data failed: ". $rc->getMessage());
     exit(1);
}

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