<?php
/**
 * Created by PhpStorm.
 * User: eater
 * Date: 6/12/16
 * Time: 3:26 PM
 */

namespace Eater\Glim\Handler\Panel\Servers;


use Eater\Glim\Handler\Session;
use Eater\Glim\Model\Certificate;
use Eater\Glim\Model\CertificateQuery;
use Eater\Glim\Model\Server;
use Eater\Glim\Model\ServerQuery;

class Config extends Session
{
    public function handle()
    {
        $zipFile = tempnam(sys_get_temp_dir(), '0zip');
        $zip = new \ZipArchive();
        $zip->open($zipFile, \ZipArchive::CREATE);
        $server = ServerQuery::create()->findOneByFingerprint($this->attr('fingerprint'));
        $name = $server->getFqdn();

        $this->fillZipWithCaAndConfig($zip, $server);

        $cert = $this->attr('cert');

        if ($cert !== null) {
            $certModel = CertificateQuery::create()->findOneByUserAndName($this->getUser(), $cert);
            $this->addClientCertificateData($zip, $certModel);

            $name .= '-' . $certModel->getName() . '.' . $certModel->getSerial();
        }

        $zip->close();

        $zipContents = file_get_contents($zipFile);
        unlink($zipFile);

        return $this->getResponse()
            ->withHeader('Content-Type', 'application/zip')
            ->withHeader('Content-Disposition', 'attachment; filename="' . $name . '.zip"')
            ->write($zipContents);
    }

    /**
     * @param \ZipArchive $zip
     * @param Server $server
     */
    public function fillZipWithCaAndConfig($zip, $server)
    {
        $config = $this->getConfigForServerFingerprint($server);
        $zip->addFromString('server.conf', $config);
        $zip->addFromString('ca.crt', file_get_contents($this->getCore()->getBaseDir() . '/storage/ca/ca.crt'));
    }

    /**
     * @param Server $server
     * @return string
     */
    public function getConfigForServerFingerprint($server)
    {
        /** @var \Twig_Environment $twig */
        $twig = $this->get('twig');

        $config = $twig->render('etc/openvpn-client.conf.twig', [
            'server' => $server
        ]);

        return $config;
    }

    /**
     * @param \ZipArchive $zip
     * @param Certificate $cert
     */
    public function addClientCertificateData($zip, $cert)
    {
        $zip->addFromString('client.crt', $cert->getCertificate());

        if ($cert->hasPrivateKey()) {
            $zip->addFromString('client.key', $cert->getPrivateKey());
        }
    }
}