<?php

try {

    $secret_key = 'Aa-1221';

    // check for POST request
    if ($_SERVER['REQUEST_METHOD'] != 'POST') {
        throw new \Exception('FAILED - not POST - '. $_SERVER['REQUEST_METHOD']);
    }
    
    // get content type
    $content_type = isset($_SERVER['CONTENT_TYPE']) ? strtolower(trim($_SERVER['CONTENT_TYPE'])) : '';
    
    if ($content_type != 'application/json') {
        throw new \Exception('FAILED - not application/json - '. $content_type);
    }
    
    // get payload
    $payload = trim(file_get_contents("php://input"));
    
    if (empty($payload)) {
        throw new \Exception('FAILED - no payload');
    }
    
    // get header signature
    $header_signature = isset($_SERVER['HTTP_X_GITEA_SIGNATURE']) ? $_SERVER['HTTP_X_GITEA_SIGNATURE'] : '';
    
    if (empty($header_signature)) {
        throw new \Exception('FAILED - header signature missing');
    }
    
    // calculate payload signature
    $payload_signature = hash_hmac('sha256', $payload, $secret_key, false);
    
    // check payload signature against header signature
    if ($header_signature !== $payload_signature) {
        throw new \Exception('FAILED - payload signature');
    }
    
    // convert json to array
    $decoded = json_decode($payload, true);
    
    // check for json decode errors
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new \Exception('FAILED - json decode - '. json_last_error());
    }
    
    exec('git pull origin dev --rebase 2>&1', $result);
    
    var_export($result);exit;
} catch (\Throwable $th) {
    var_export($th->getMessage());
}