1<?php
2/**
3 * Copyright (c) 2014 Robin Appelman <icewind@owncloud.com>
4 * This file is licensed under the Licensed under the MIT license:
5 * http://opensource.org/licenses/MIT
6 */
7
8namespace Icewind\SMB;
9
10use Icewind\SMB\Exception\Exception;
11
12class System implements ISystem {
13	/** @var (string|null)[] */
14	private $paths = [];
15
16	/**
17	 * Get the path to a file descriptor of the current process
18	 *
19	 * @param int $num the file descriptor id
20	 * @return string
21	 * @throws Exception
22	 */
23	public function getFD(int $num): string {
24		$folders = [
25			'/proc/self/fd',
26			'/dev/fd'
27		];
28		foreach ($folders as $folder) {
29			if (file_exists($folder)) {
30				return $folder . '/' . $num;
31			}
32		}
33		throw new Exception('Cant find file descriptor path');
34	}
35
36	public function getSmbclientPath(): ?string {
37		return $this->getBinaryPath('smbclient');
38	}
39
40	public function getNetPath(): ?string {
41		return $this->getBinaryPath('net');
42	}
43
44	public function getSmbcAclsPath(): ?string {
45		return $this->getBinaryPath('smbcacls');
46	}
47
48	public function getStdBufPath(): ?string {
49		return $this->getBinaryPath('stdbuf');
50	}
51
52	public function getDatePath(): ?string {
53		return $this->getBinaryPath('date');
54	}
55
56	public function libSmbclientAvailable(): bool {
57		return function_exists('smbclient_state_new');
58	}
59
60	protected function getBinaryPath(string $binary): ?string {
61		if (!isset($this->paths[$binary])) {
62			$result = null;
63			$output = [];
64			exec("which $binary 2>&1", $output, $result);
65			$this->paths[$binary] = $result === 0 ? trim(implode('', $output)) : null;
66		}
67		return $this->paths[$binary];
68	}
69}
70