<?php

namespace App\Console\Commands;
use Illuminate\Console\Command;

class MakeNginxConfCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    //部署文件目录名称，需手动输入
    protected $signature = 'make:nginx-conf {dir}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动生成nginx配置文件';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $url = config('app.web_url');
        $parsedUrl = parse_url($url);
        $host = $parsedUrl['host'];
        $dir = $this->argument('dir');
        $project = base_path();
        $project = explode('/', $project);
        array_pop($project);
        $project[] = $dir;
        $project = implode('/', $project);
        $certKey = resource_path('cert').'/apiclient_key.pem';
        $certPem = resource_path('cert').'/apiclient_cert.pem';
        $conf =
'server {
    listen       80;
    server_name ' . $host . ';
    return 301 https://' . $host . '$request_uri;
}
server{
    listen               443 ssl;
    server_name ' . $host . ';
    ssl_certificate "'.$certPem.'";
    ssl_certificate_key "'.$certKey.'";
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    index index.html index.htm index.php;
    root  ' . $project . '/public;

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location /resources/ {
                alias  "' . $project . '/resources/upload/";
        }
        location /admin_me_15446 {
                 alias "' . $project . '/public/dist";
                index  index.html;
        }

        location /static/ {
                alias "' . $project . '/public/dist/static/";
        }
        location / {
                try_files $uri $uri/ /index.php?$query_string;
        }
        location ~ .*\.(php|php5)?$
        {
                index  index.html index.htm index.php;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi.conf;
        }
}';
        $path = resource_path('conf/');
        if (!is_dir($path)) {
            mkDirs($path);
        }
        $fileName = $path . $dir .'_nginx.conf';
        file_put_contents($fileName, $conf);
        echo 'echo "include '.$fileName.';" >> /etc/nginx/nginx.conf'.PHP_EOL;
    }
}
