<?php

class smpushpid {

  protected $filename;
  public $already_running = false;

  function __construct($directory) {
    global $wp_filesystem;

    $this->filename = $directory . '/' . basename($_SERVER['PHP_SELF']) . '.pid';
    if($wp_filesystem->is_writable($this->filename) || $wp_filesystem->is_writable($directory)) {
      if($wp_filesystem->exists($this->filename)) {
        $pid = (int)trim(smpush_helper::readFile($this->filename));
        if(posix_kill($pid, 0)) {
          $this->already_running = true;
        }
      }
    }
    else {
      die("Cannot write to pid file '$this->filename'. Program execution halted.\n");
    }

    if(!$this->already_running) {
      $pid = getmypid();
      smpush_helper::storeFile($this->filename, $pid);
    }
  }

  public function __destruct() {
    if(!$this->already_running) {
      smpush_unlink($this->filename);
    }
  }

}
