<?php

namespace LakeDrops\DockerTraefik;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Yaml\Yaml;

/**
 * Class Traefik.
 *
 * @package LakeDrops\DockerTraefik
 */
class Traefik {

  /**
   * The name of the project using Traefik.
   *
   * @var string
   */
  protected $name;

  /**
   * Traefik constructor.
   *
   * @param string $name
   *   Name of the network to be created which needs to match the container
   *   prefix of your project you would like to handle with Traefik.
   */
  public function __construct($name) {
    $this->name = $name;
  }

  /**
   * Update the Traefik container.
   */
  public function update() {
    // Update host wider traefik container.
    $traefikPath = $_SERVER['HOME'] . '/.traefik';
    $traefikFile = $traefikPath . '/docker-compose.yml';

    /* @var FileSystem $fs */
    $fs = new Filesystem();
    if ($fs->exists($traefikFile)) {
      $traefik = Yaml::parse(file_get_contents($traefikFile));
    }
    else {
      $fs->mkdir($traefikPath);
      $traefik = [
        'version' => '3',
        'services' => [
          'traefik' => [
            'image' => 'traefik:1.7.17',
            'restart' => 'unless-stopped',
            'command' => '-c /dev/null --web --docker --logLevel=DEBUG',
            'networks' => [],
            'ports' => [
              '8000:80',
            ],
            'volumes' => [
              '/var/run/docker.sock:/var/run/docker.sock',
            ],
          ],
        ],
        'networks' => [],
      ];
    }

    if (!in_array($this->name, $traefik['services']['traefik']['networks'], TRUE)) {
      $traefik['services']['traefik']['networks'][] = $this->name;
      $traefik['networks'][$this->name] = [
        'driver' => 'bridge',
      ];
      file_put_contents($traefikFile, Yaml::dump($traefik, 9, 2));
      $cwd = getcwd();
      chdir($traefikPath);
      exec('docker-compose --project-name traefik up -d');
      chdir($cwd);
    }
  }

}