<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-OPS-KEY');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
$KEY = 'Sumon160@';
$key = $_POST['key'] ?? $_GET['key'] ?? ($_SERVER['HTTP_X_OPS_KEY'] ?? '');
if ($key !== $KEY) { http_response_code(401); echo json_encode(['ok'=>false,'error'=>'unauthorized']); exit; }
$action = $_POST['action'] ?? $_GET['action'] ?? '';
$root = __DIR__;
function safe_list($dir){ $out=[]; $items=@scandir($dir); if(!$items){ return $out; } foreach($items as $it){ if($it==='.'||$it==='..') continue; $p=$dir.DIRECTORY_SEPARATOR.$it; $out[]=['name'=>$it,'type'=>is_dir($p)?'dir':'file','size'=>is_file($p)?filesize($p):0]; } return $out; }
function rrmdir_ops($dir,$keep){ $items=@scandir($dir); if(!$items){ return; } foreach($items as $it){ if($it==='.'||$it==='..') continue; if(in_array($it,$keep,true)) continue; $p=$dir.DIRECTORY_SEPARATOR.$it; if(is_dir($p)){ rrmdir_ops($p,[]); @rmdir($p); } else { @unlink($p); } } }
function extract_zip_ops($zip,$target){ $z=new ZipArchive(); if($z->open($zip)===TRUE){ $z->extractTo($target); $z->close(); @unlink($zip); return true; } return false; }
if ($action==='list'){ echo json_encode(['ok'=>true,'items'=>safe_list($root)]); exit; }
if ($action==='clean'){ rrmdir_ops($root,['deploy_manager.php','ops_api.php','.htaccess','index.php','health.php']); echo json_encode(['ok'=>true,'message'=>'cleaned']); exit; }
if ($action==='fetch'){ $url=trim($_POST['zip_url'] ?? $_GET['zip_url'] ?? ''); if(!$url){ echo json_encode(['ok'=>false,'error'=>'zip_url required']); exit; } $tmp=$root.DIRECTORY_SEPARATOR.'__ops.zip'; $data=@file_get_contents($url); if($data===false){ echo json_encode(['ok'=>false,'error'=>'download failed']); exit; } file_put_contents($tmp,$data); if(extract_zip_ops($tmp,$root)){ echo json_encode(['ok'=>true,'message'=>'fetched']); } else { echo json_encode(['ok'=>false,'error'=>'extract failed']); } exit; }
if ($action==='upload' && isset($_FILES['zip'])){ $tmp=$root.DIRECTORY_SEPARATOR.'__ops_up.zip'; if(move_uploaded_file($_FILES['zip']['tmp_name'],$tmp)){ if(extract_zip_ops($tmp,$root)){ echo json_encode(['ok'=>true,'message'=>'uploaded']); } else { echo json_encode(['ok'=>false,'error'=>'extract failed']); } } else { echo json_encode(['ok'=>false,'error'=>'upload failed']); } exit; }
echo json_encode(['ok'=>false,'error'=>'invalid action']);

