<?php

$config = json_decode(file_get_contents("/var/www/usergen/secret/config.json", true));

require_once("/var/www/usergen/secret/helpers.php");
require_once("/var/www/usergen/secret/oauth.php");
require_once("/var/www/usergen/secret/rsa.php");

if (isset($_REQUEST["act"])) {
    // internal functions such as id request
    switch($_REQUEST["act"]){
        case "id":
            // return OAUTH app ID
            header('Content-type: application/json');
            echo json_encode(array("id" => $config->oauth->key));
            exit();
            break;
        case "login":
            if (isset($_REQUEST["code"])){
                // Mastodon callback (Authorization Code from /oauth/authorize)
                $authCode = $_REQUEST["code"];
                $Auth = oauthToken($authCode, $config);
                if(isset($Auth->token_type)){
                    // Valid Auth?
                    $User = verifyCredentials($Auth->access_token);
                    if (gettype($User) == "object" && isset($User->id)) {
                        // Congrats!
                        returnSuccess($User, buildEncToken($Auth->access_token, $User->id, $_SERVER["REMOTE_ADDR"], $_SERVER["HTTP_USER_AGENT"]));
                    }else{
                        // invalid auth
                        // $User contains error string
                        returnError($User);
                    }
                }else{
                    // invalid auth
                    returnError($Auth);
                }
            }else{
                returnError("Incorrect Login Query");
            }
            break;
        case "verify":
            if (isset($_REQUEST["token"])){
                // Verify Encrypted Token
                $EncTokenData = $_REQUEST["token"];
                $TokenData = verifyEncToken($EncTokenData);
                if (gettype($TokenData) == "string") {
                    // Invalid Token
                    returnError($TokenData);
                }else{
                    // Valid Token
                    returnSuccess($TokenData["MastodonData"],
                        buildEncToken($TokenData["AuthToken"],
                            $TokenData["UserID"],
                            $_SERVER["REMOTE_ADDR"],
                            $_SERVER["HTTP_USER_AGENT"]
                        )
                    );
                }
            }else{
                returnError("Incorrect Verify Query");
            }
            break;
        default:
            returnError("Incorrect Action Query");
            break;
    }
}else {
    returnError("Incorrect Empty Query");
}
?>
