<?php 
// apple_script_url.php
// RJM Programming
// February 2022

$ts=date('_dmY_his', time());

if (isset($argc)) {
  if (PHP_OS == "Darwin") { 
    if ($argc >= 2) {
     if (file_exists(getenv('HOME') . '/Desktop/MyAppleScript' . $ts . '.scpt')) {
       unlink(getenv('HOME') . '/Desktop/MyAppleScript' . $ts . '.scpt');
     }
     file_put_contents(getenv('HOME') . '/Desktop/MyAppleScript' . $ts . '.scpt', "tell application \"Terminal\"\n	activate\n	do script \"cd '" . getenv('HOME') . '/Desktop' . "'\" in window 1\n	do script \"open '" . $argv[1] . "'\" in window 1\nend tell");
     exec("cd " . getenv('HOME') . '/Desktop ; open MyAppleScript' . $ts . '.scpt');
    }
  }
} else if (isset($_GET['url'])) {
  if (PHP_OS == "Darwin") { 
    if (file_exists(getenv('HOME') . '/Desktop/MyAppleScript' . $ts . '.scpt')) {
       unlink(getenv('HOME') . '/Desktop/MyAppleScript' . $ts . '.scpt');
    }
    file_put_contents(getenv('HOME') . '/Desktop/MyAppleScript' . $ts . '.scpt', "tell application \"Terminal\"\n	activate\n	do script \"cd '" . getenv('HOME') . '/Desktop' . "'\" in window 1\n	do script \"open '" . str_replace('+','%20',$_GET['url']) . "'\" in window 1\nend tell");
    //exec('open \"' . getenv('HOME') . '/Desktop/MyAppleScript' . $ts . '.scpt\"');
    passthru("cd " . getenv('HOME') . '/Desktop ; open MyAppleScript' . $ts . '.scpt');
  } else if (strpos($_SERVER['SERVER_NAME'], 'localhost') === false) {
    echo "<html><body onload=\" window.open('HTTP://localhost:8888/apple_script_url.php?url=" . str_replace('+','%20',$_GET['url']) . "','_self');  \"></body></html>";
  }
}
?>