<?php
	/**
	 * GIT DEPLOYMENT SCRIPT
	 *
	 * Used for automatically deploying websites via github or bitbucket, more deets here:
	 * https://gist.github.com/riodw/71f6e2244534deae652962b32b7454e2
	 * How To Use:
	 * https://medium.com/riow/deploy-to-production-server-with-git-using-php-ab69b13f78ad
	 */
	// The commands
	
	$output = "";
	$payloadRef = null;

	if(!empty($_POST['payload'])){
	 $payload = json_decode($_POST['payload']);
	 $payloadRef = $payload->ref;
	}else{
	 $_POST = json_decode(file_get_contents('php://input'), true);
	 if (!empty($_POST["ref"])) {
	  $payloadRef = $_POST["ref"];
	 }
	}
	
	if (!empty($payloadRef)) {
	 
	 $commands = array(
	  'echo $PWD',
	  'whoami',
	  'git rm $(git ls-files --deleted)',
	  'git stash -u',
	  'git reset --hard @{u}',
	  'git fetch',
	  'git pull',
	  'git stash pop',
	  'git status',
	 );
	 // Run the commands for output
	 $output = '';
	 
	 if($payloadRef = "refs/heads/master"){
	  foreach($commands AS $command){
		  // Run it
		  $tmp = shell_exec($command);
		  // Output
		  $output .= "<span style=\"color: #6BE234;\">\$</span> <span style=\"color: #729FCF;\">{$command}\n</span>";
		  $output .= htmlentities(trim($tmp)) . "\n";
	  }
	 }else{
	  header("HTTP/1.0 204 No Content");
	  echo "Reference is not for master branch";
	  exit;
	 }
	 // Make it pretty for manual user access (and why not?)
	}else{
	 header("HTTP/1.0 204 No Content");
	 echo "Reference is not set";
	 exit;
	}
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title>GIT DEPLOYMENT SCRIPT</title>
</head>
<body style="background-color: #000000; color: #FFFFFF; font-weight: bold; padding: 0 10px;">
<pre>
 ____________________________
|                            |
| Git Deployment Script v0.1 |
|      github.com/riodw 2017 |
|____________________________|

<?php echo $output; ?>
</pre>
</body>
</html>