<?php

/**
 * Class BaseDataImporter
 */
abstract class BaseDataImporter implements ImportDataInterface
{
    protected $username;
    protected $ci;
    protected $db;
    protected $settingsDb;
    protected $phar;
    protected $skipDuplicates;
    private $cfengineScriptsDir = '/opt/cfengine/notification_scripts/';
    protected $isAdmin;
    protected $encryptionKey;

    public function __construct()
    {
        $this->ci = get_instance();
    }

    public function setEncryptionKey($v)
    {
        $this->encryptionKey = $v;
        return $this;
    }

    public function setIsAdmin($v)
    {
        $this->isAdmin = $v;
        return $this;
    }

    public function setUsername($username)
    {
        $this->username = $username;
        return $this;
    }

    public function setDbInstance($instance)
    {
        $this->db = $instance;
        return $this;
    }

    public function setSettingsDbInstance($instance)
    {
        $this->settingsDb = $instance;
        return $this;
    }

    public function setPharObject($phar)
    {
        $this->phar = $phar;
        return $this;
    }

    protected function saveScripts()
    {
        if (isset($this->phar['notification_scripts']) && !empty($this->phar['notification_scripts'])) {
            $scriptsPhar = new Phar($this->phar['notification_scripts']->getPathname());
            $notificationScriptsDir = $this->cfengineScriptsDir;
            if (!is_dir($notificationScriptsDir)) {
                mkdir($notificationScriptsDir);
            }

            foreach ($scriptsPhar as $script) {
                file_put_contents($this->cfengineScriptsDir . $script->getFileName(), $script->getContent());
            }

            $this->setScriptsPermissions($notificationScriptsDir);
        }
    }

    public function setSkipDuplicates($v)
    {
        $this->skipDuplicates = $v;
        return $this;
    }

    protected function setScriptsPermissions($path)
    {
        if (is_dir($path)) {
            $dir = new DirectoryIterator($path);
            foreach ($dir as $item) {
                if ($item->isFile()) {
                    chmod($item->getPathname(), 0754);
                }
            }
        } else {
            chmod($path, 0754);
        }
    }
}
