From cabc0eb71d107b8200badcc01f2b7e147a522ac6 Mon Sep 17 00:00:00 2001 From: Tony Murray Date: Thu, 11 Jan 2018 16:19:13 -0600 Subject: [PATCH] feature: Quick script to rename mibs to their proper names (#8068) So I can stop re-writing it ;) --- scripts/rename-mibs.php | 82 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 scripts/rename-mibs.php diff --git a/scripts/rename-mibs.php b/scripts/rename-mibs.php new file mode 100644 index 0000000000..10744b8a83 --- /dev/null +++ b/scripts/rename-mibs.php @@ -0,0 +1,82 @@ +. + * + * @package LibreNMS + * @link http://librenms.org + * @copyright 2018 Tony Murray + * @author Tony Murray + */ + +array_shift($argv); // remove script name + +if (empty($argv)) { + echo "You must specify one or more files or folders containing files to rename.\n"; +} + +foreach ($argv as $item) { + if (is_dir($item)) { + foreach (scandir($item) as $file) { + rename_mib_file($file); + } + } else { + rename_mib_file($item); + } +} + + +function rename_mib_file($file) +{ + if (!is_file($file)) { + echo "Not a file: $file\n"; + return; + } + + $mib_name = extract_mib_name($file); + $filename = basename($file); + if ($mib_name != $filename) { + $new_file = dirname($file) . '/' . $mib_name; + echo "$file -> $new_file\n"; + rename($file, $new_file); + } +} + +function extract_mib_name($file) +{ + // extract the mib name (tried regex, but was too complex and I had to read the whole file) + if ($handle = fopen($file, "r")) { + $header = ''; + while (($line = fgets($handle)) !== false) { + $trimmed = trim($line); + + if (empty($trimmed) || substr($trimmed, 0, 2) == '--') { + continue; + } + + $header .= " $trimmed"; + if (strpos($trimmed, 'DEFINITIONS') !== false) { + preg_match('/(\S+)\s+(?=DEFINITIONS)/', $header, $matches); + fclose($handle); + return $matches[1]; + } + } + fclose($handle); + } + + throw new Exception("Could not extract mib name from file ($file)"); +}