<?php
/* * ********************************************************************
*  ProxmoxVPS Product developed. (27.03.19)
* *
*
*  CREATED BY MODULESGARDEN       ->       http://modulesgarden.com
*  CONTACT                        ->       contact@modulesgarden.com
*
*
* This software is furnished under a license and may be used and copied
* only  in  accordance  with  the  terms  of such  license and with the
* inclusion of the above copyright notice.  This software  or any other
* copies thereof may not be provided or otherwise made available to any
* other person.  No title to and  ownership of the  software is  hereby
* transferred.
*
*
* ******************************************************************** */

namespace ModulesGarden\Servers\ProxmoxVps\App\UI\Reinstall\Providers;


use MGProvision\Proxmox\v2\repository\SnapshotRepository;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\HighAvailabilityClusterService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\IpSetIpFilterService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;

class IsoInstallProvider extends BaseDataProvider implements ClientArea
{
    use ProductService;
    use ApiService;
    /**
     * @var HighAvailabilityClusterService
     */
    private $highAvailabilityClusterService;
    /**
     * @var IpSetIpFilterService
     */
    private $ipSetIpFilterService;

    public function read()
    {
        if ($this->actionElementId)
        {
            $this->data['id'] = $this->actionElementId;
        }
    }

    public function update()
    {

    }

    private function initServices()
    {
        $this->highAvailabilityClusterService = new HighAvailabilityClusterService();
        $this->ipSetIpFilterService           = new IpSetIpFilterService();
    }

    public function processQemu()
    {
        $this->initServices();
        //Empyty template
        if (!$this->formData['id'])
        {
            throw new \Exception ("Provide OS Template");
        }
        $spanshootRepostiory = new SnapshotRepository();
        $spanshootRepostiory->findByVm($this->vm())
            ->ignoreCurrent(true);
        if ($spanshootRepostiory->count())
        {
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('Remove the snapshots before reinstallation.');
        }
        //ha
        if ($this->highAvailabilityClusterService->exist())
        {
            $this->highAvailabilityClusterService->delete();
        }
        //stop
        if ($this->vm()->isRunning())
        {
            $this->vm()->stop();
        }
        //Remove cloud-init drive
        foreach ($this->vm()->config() as $id => $v)
        {
            if (preg_match('/cloudinit/', $v))
            {
                $this->vm()->deleteConfig($id);
            }
        }
        //insert unattended iso
        $this->vm()->changeIso($this->formData['id']);
        //remove hard drive and recreate a new one, (the drive have to be empty)
        $masterHdd = $this->vm()->getMasterHardDisk();
        $masterHdd->delete();
        sleep(1);
        //Delete Unused Disk
        foreach ($this->vm()->config(true) as $id => $v)
        {
            if (preg_match('/unused/', $id))
            {
                $this->vm()->deleteConfig($id);
            }
        }
        //create new disk
        $bytes = $masterHdd->getBytes();
        $size  = (int)$bytes / pow(1024, 3);
        $masterHdd->setSize($size);
        $masterHdd->create();
        sleep(1);
        //Boot disk
        $this->vm()->updateConfig(['bootdisk' => $masterHdd->getId()]);
        //set bootorder to disk, cdrom, network (if cdrom would be first, the installer will run on every boot -> bootloop)
        $this->vm()->changeBootOrder('cdn');
        //ipset
        if ($this->configuration()->isIpsetIpFilter())
        {
            $this->ipSetIpFilterService->create();
        }
        //HA
        if ($this->configuration()->getClusterState())
        {
            $this->highAvailabilityClusterService->create();
        }
        //start vps
        $this->vm()->start();
        //show message that installation is now processing. The login information will be available in the noVNC console after installation.
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('Installation is now processing. The login information will be available in the noVNC console.');

    }

}