<?php
require 'vendor/autoload.php';

$posts = array();
$postDir = __DIR__.'/views/posts/';
foreach (scandir($postDir) as $filename) {
   $post = parsePost($postDir, $filename);

   if ($post != null) {
      $posts[$post->posted->timestamp] = $post;
   }
}

ksort($posts);
writePosts($posts, __DIR__.'/posts.php');

function parsePost($dir, $filename)
{
   $posts = array();

   if (preg_match('/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})-(.+)\.php$/', $filename, $matches) === 1) {
      $posted = \Carbon\Carbon::create($matches[1], $matches[2], $matches[3], 12);
      $slug = $matches[4];
      $title = getPostTitle($dir.$filename);
      if (strlen($title) > 0) {
         return new Post($title, $slug, $posted);
      }
   }

   return null;
}

function getPostTitle($file)
{
   $lines = file($file);
   if (preg_match('@^\<\?\/\*(.+)\*\/\?\>$@', trim($lines[0]), $matches) === 1) {
      return $matches[1];
   }

   return null;
}

function writePosts($posts, $file)
{
   $s  = '<?php' . PHP_EOL . PHP_EOL;
   $s .= '/***** This code is autogenerated by the "genposts.php" script.  Do not hand modify this code! *****/'. PHP_EOL . PHP_EOL;
   $s .= '$postData = array();' . PHP_EOL . PHP_EOL;

   foreach ($posts as $post) {
      $s .= sprintf('$postData[] = new Post(\'%s\', "%s", \Carbon\Carbon::createFromTimestamp(%d));%s', str_replace("'", "\\'", $post->title), $post->slug, $post->posted->timestamp, PHP_EOL);
   }

   $s .= <<<'__POST__'

$posts = new Posts();
foreach($postData as $post)
{
   $posts->add($post);
}

return $posts;

/***** This code is autogenerated by the "genposts.php" script.  Do not hand modify this code! *****/
__POST__;

   file_put_contents($file, $s);
}
