<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class BashController extends Controller {
  public function exec (Request $r) { // /api/rpc/bash/exec
    if (strlen($r->args) == 0) return '';
    $args = explode(' ', $r->args);
    if ($args[0] == 'ls') {
      return $this->ls($args);
    }
    else if ($args[0] == 'cat') {
      return $this->cat($args);
    }

    return '不明なコマンドです。: '.$args[0];
  }

  public function ls ($args) {
    $opt = '';
    $pwd = '';

    for ($i = 1; $i < count($args); $i++) {
      if (mb_substr($args[$i], 0, 1, 'utf-8')) $opt = $args[$i];
    }

    if (strpos($opt, 'l') !== false) {
      $ps = null;
      $pg = null;

      if (strpos($opt, 't') !== false) {
        $pg = DB::table('blg_content')->select('publish_date')->where('isPost', 0)->orderBy('title', 'asc')->first();
        $ps = DB::table('blg_content')->select('publish_date')->where('isPost', 1)->orderBy('title', 'asc')->first();
      }
      else {
        $pg = DB::table('blg_content')->select('publish_date')->where('isPost', 0)->orderBy('publish_date', 'desc')->first();
        $ps = DB::table('blg_content')->select('publish_date')->where('isPost', 1)->orderBy('publish_date', 'desc')->first();
      }

      return "合計 2<br />
drwxr-xr-x  2 suwako suwako  ".(strpos($opt, 'h') !== false ? '4.0K' : '4096')."  ".date('m', $ps->publish_date)."月 ".date('d', $ps->publish_date)." ".date('H:i', $ps->publish_date)."  post<br />
drwxr-xr-x  2 suwako suwako  ".(strpos($opt, 'h') !== false ? '4.0K' : '4096')."  ".date('m', $pg->publish_date)."月 ".date('d', $pg->publish_date)." ".date('H:i', $pg->publish_date)."  page";
    }

    return 'post page';
  }

  public function cat ($args) {
    if (isset($args[1])) {
      $cat = explode('/', $args[1]);
      $txt = null;
      $mode = 0;
      $slug = '';

      for ($i = 1; $i < count($cat); $i++) {
        if (strpos($cat[$i], 'post') !== false) $mode = 1;
        $slug = $cat[$i];
      }

      $txt = DB::table('blg_content')->select('title', 'message')->where('slug', $slug)->where('isPost', $mode)->first();

      if ($txt) {
      return "＞＞".$txt->title."＜＜<br /><br />
".$txt->message;
      }
    }

    return '';
  }
}
