1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 371: 372: 373: 374: 375: 376: 377: 378: 379: 380: 381: 382: 383: 384: 385: 
<?php
    declare(strict_types=1);
    /**
     *  +------------------------------------------------------------+
     *  | apnscp                                                     |
     *  +------------------------------------------------------------+
     *  | Copyright (c) Apis Networks                                |
     *  +------------------------------------------------------------+
     *  | Licensed under Artistic License 2.0                        |
     *  +------------------------------------------------------------+
     *  | Author: Matt Saladna (msaladna@apisnetworks.com)           |
     *  +------------------------------------------------------------+
     */

    use Opcenter\Versioning;

    /**
     * Ruby, RoR features formerly under Web_Module
     *
     * @package core
     */
    class Ruby_Module extends Module_Skeleton
    {
        const LTS = '2.5.3';
        public $exportedFunctions = [
            '*'             => PRIVILEGE_SITE | PRIVILEGE_USER,
            'update_remote' => PRIVILEGE_ADMIN
        ];

        public function __construct()
        {
            if (!platform_is('7.5')) {
                $this->exportedFunctions = [];
            }
            parent::__construct();
        }

        /**
         * Execute Ruby within the scope of a version
         *
         * @param null|string $version
         * @param null|string $pwd pwd, defaults to ~
         * @param string      $command
         * @param array       $args optional command arguments
         * @return array process output from pman_run
         */
        public function do(?string $version, ?string $pwd, string $command, ...$args): array
        {
            if ($version === 'lts') {
                $version = $this->get_lts();
            }

            if (!$pwd) {
                $pwd = '~';
            }

            $args[0]['_RUBY_PWD'] = $pwd ?? '~';

            if (!isset($args[1])) {
                $args[1] = [];
            }
            if ($version) {
                $args[1] += [
                    'RBENV_VERSION' => $version
                ];
            }

            $ret = $this->pman_run('/bin/bash -ic -- ' . escapeshellarg('cd %(_RUBY_PWD)s' . ' && rbenv rehash && rbenv exec ' . $command),
                ...$args);
            if (!$ret['success']) {
                // no job control warning
                error(coalesce($ret['stderr'], $ret['stdout']));
            }

            return $ret;
        }

        /**
         * Get configured Ruby LTS
         *
         * @return string
         */
        protected function get_lts(): string
        {
            $prefs = \Preferences::factory($this->getAuthContext());

            return array_get($prefs, 'ruby.lts', static::LTS);
        }

        /**
         * Update known Ruby versions
         *
         * @return bool
         */
        public function update_remote(): bool
        {
            if (!IS_CLI) {
                return $this->query('ruby_update_remote');
            }
            // @TODO move to private repo lest we have an "event-stream" debacle
            $builddir = $this->getRbenvRoot() . '/plugins/ruby-build';
            $ret = \Util_Process_Safe::exec('cd %(builddir)s && git pull', ['builddir' => $builddir]);
            if (!$ret['success']) {
                return error(coalesce($ret['stderr'], $ret['stdout']));
            }
            (new \Opcenter\Service\ServiceLayer(null))->dropVirtualCache();

            return true;
        }

        /**
         * Get rbenv root
         *
         * @return null|string
         */
        protected function getRbenvRoot(): ?string
        {
            $ret = \Util_Process_Safe::exec('/bin/bash -ic "rbenv root"');

            return $ret['success'] ? trim($ret['stdout']) : null;
        }

        /**
         * Remove an installed Ruby
         *
         * @param string $version
         * @return bool
         */
        public function uninstall(string $version): bool
        {
            if ($version === 'lts') {
                $version = $this->get_lts();
            }
            $ret = $this->exec('uninstall -f', $version);
            if (!$ret['success']) {
                return error('failed to uninstall Ruby %s: %s',
                    $version,
                    coalesce($ret['stderr'], $ret['stdout'])
                );
            }

            return true;
        }

        /**
         * nvm wrapper
         *
         * @param null|string $name
         * @param null|string $command
         * @param array       $args optional args
         * @return array
         */
        private function exec(?string $name, string $command = null, ...$args): array
        {
            $ret = $this->pman_run('/bin/bash -ic -- ' . escapeshellarg("rbenv ${name} ${command}"),
                $args,
                [
                    'BASH_ENV' => '/dev/null'
                ]
            );

            return $ret;
        }

        /**
         * Assign Ruby version to directory
         *
         * @param string $version
         * @param string $path
         * @return bool
         */
        public function make_default(string $version, string $path = '~'): bool
        {
            if ($version === 'lts') {
                $version = $this->get_lts();
            }
            $path .= '/.ruby-version';

            return $this->file_put_file_contents($path, $version, true);
        }

        /**
         * Ruby version inferred from path
         *
         * @param string $path
         * @return string
         */
        public function version_from_path(string $path): string
        {
            $rbfile = $path . '/.ruby-version';
            if ($this->file_exists($rbfile)) {
                return trim($this->file_get_file_contents($rbfile));
            }
            $output = $this->pman_run('cd %(path)s && /bin/bash -ic "rbenv version"', ['path' => $path]);

            return $output['success'] ? strtok($output['stdout'], ' ') : 'system';
        }

        /**
         * Install Ruby
         *
         * @param string $version
         * @return bool
         */
        public function install(string $version): bool
        {
            if ($version === 'lts') {
                $version = $this->get_lts();
            }
            $ret = $this->exec('install', $version);
            if (!$ret['success']) {
                return error('failed to install Ruby %s, error: %s',
                    $version,
                    coalesce($ret['stderr'], $ret['stdout'])
                );
            }

            return true;
        }

        /**
         * Ruby version is installed
         *
         * @param string $version
         * @return bool
         */
        public function installed(string $version): bool
        {
            if ($version === 'lts') {
                return $this->lts_installed();
            }
            $nodes = $this->list();

            foreach ($nodes as $alias => $localVersion) {
                if ($alias === $version) {
                    return true;
                }

                if ($version === $localVersion ||
                    (false !== strpos($localVersion, '.') && Versioning::compare($version, $localVersion, '='))) {
                    return true;
                }
            }

            return false;
        }

        /**
         * Latest LTS is installed
         *
         * @return bool
         */
        public function lts_installed(): bool
        {
            $versions = $this->list();

            return \in_array($this->get_lts(), $versions, true);
        }

        /**
         * List installed Rubys
         *
         * @return array
         */
        public function list(): array
        {
            // 3 = no nodes installed
            $ret = $this->exec('versions');
            $rubies = [];
            if (preg_match_all('/^(?>(?<default>\S+)|\s+)\s*(?<version>\S+)(?>$|\s*)(?<misc>[^\r\n]*)$/m',
                $ret['output'], $versions, PREG_SET_ORDER)) {
                foreach ($versions as $v) {
                    $rubies[] = $v['version'];
                    if (isset($v['default'])) {
                        $rubies['active'] = $v['version'];
                    }
                }

                return $rubies;
            }

            return [];
        }

        /**
         * Get available Rubies
         *
         * @return array
         */
        public function get_available(): array
        {
            $cache = \Cache_Super_Global::spawn();
            $key = 'ruby.rem';
            if (false !== ($res = $cache->get($key))) {
                return $res;
            }
            $ret = $this->exec('install --list');
            if (!$ret['success']) {
                error('failed to query Rubies - is rbenv installed?');

                return [];
            }
            $rubies = [];
            strtok($ret['output'], "\n ");
            while (false !== ($ruby = strtok("\n "))) {
                $rubies[] = $ruby;
            }

            $cache->set($key, $rubies);

            return $rubies;
        }

        public function _edit()
        {
            $conf_cur = $this->getAuthContext()->conf('ssh', 'cur');
            $conf_new = $this->getAuthContext()->conf('ssh', 'new');
            if (!version_compare(platform_version(), '6', '>=')) {
                return;
            }
            if ($conf_new['enabled'] && !$conf_cur['enabled']) {
                $this->initialize_gemset();
            }
        }

        public function initialize_gemset($user = null)
        {
            if (platform_is('7.5')) {
                return true;
            }
            if (!IS_CLI) {
                return $this->query('ruby_initialize_gemset', $user);
            }
            if (!is_dir(FILESYSTEM_SHARED . '/ruby')) {
                // Ruby not configured on platform
                return info('skipping rvm initialization - ruby not configured on platform');
            }
            if (!version_compare(platform_version(), '6', '>=')) {
                return info('gemset unsupported on platform v%d', platform_version());
            }
            if (!$user || !($this->permission_level & PRIVILEGE_SITE)) {
                $user = $this->username;
            }

            if (!$this->user_exists($user)) {
                return error("invalid user `%s'", $user);
            }
            if (!$this->misc_procfs_enabled()) {
                return -1;
            }

            $proc = new Util_Process_Sudo();
            $proc->setOption('user', $user);
            $ret = $proc->run('/bin/bash -i rvm user gemsets');
            if (!$ret['success']) {
                return error("error initializing gemset: `%s'", $ret['stderr']);
            }

            return $ret['success'];
        }

        public function _create()
        {
            $conf_new = $this->getAuthContext()->conf('ssh', 'new');
            if (!$conf_new['enabled']) {
                return true;
            }
            if (version_compare(platform_version(), '6', '>=')) {
                $this->initialize_gemset();
            }

        }

        /**
         * Set LTS for account
         *
         * @param string $version
         */
        protected function set_lts(string $version): void
        {
            $prefs = \Preferences::factory($this->getAuthContext());
            $prefs->unlock($this->getApnscpFunctionInterceptor());
            array_set($prefs, 'ruby.lts', $version);
        }
    }