<?php

namespace Eater\Glim\Handler\Install;

use Eater\Glim\Service\User;

class Action extends Show
{
    public function handle()
    {
        /** @var User $user */
        $user = $this->get('user');

        $caCN = $this->post('ca-cn');

        /* @var \Aura\Session\Session $session */
        $session = $this->get('session');
        $segment = $session->getSegment('main');

        if (trim($caCN) === "") {
            $segment->setFlash('error', 'CA Common name can\'t be empty');
            return $this->redirect('/install');
        }

        /** @var \Twig_Environment $twig */
        $twig = $this->get('twig');

        $opensslConf = $twig->render('etc/openssl-ca.conf.twig', [
            'host' => $this->post('domainWithPort')
        ]);

        file_put_contents($this->getCore()->getBaseDir() . '/etc/openssl.conf', $opensslConf);

        exec($this->getCore()->getBaseDir() . '/bin/clean-all');
        exec($this->getCore()->getBaseDir() . '/bin/setup ' . escapeshellarg($caCN));

        $newUser = null;

        try {
            $newUser = $user->createSuperuser($this->post('username'), $this->post('password'));
        } catch (\Exception $e) {
            $segment->setFlash("error", $e->getMessage());
        }

        if ($newUser === null) {
            return $this->redirect('/install');
        }

        $segment->set('user', $newUser);

        return $this->redirect('/panel');
    }
}