1/*
2** Zabbix
3** Copyright (C) 2001-2021 Zabbix SIA
4**
5** This program is free software; you can redistribute it and/or modify
6** it under the terms of the GNU General Public License as published by
7** the Free Software Foundation; either version 2 of the License, or
8** (at your option) any later version.
9**
10** This program is distributed in the hope that it will be useful,
11** but WITHOUT ANY WARRANTY; without even the implied warranty of
12** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13** GNU General Public License for more details.
14**
15** You should have received a copy of the GNU General Public License
16** along with this program; if not, write to the Free Software
17** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18**/
19
20package alias
21
22import (
23	"fmt"
24	"strings"
25
26	"zabbix.com/internal/agent"
27	"zabbix.com/pkg/itemutil"
28)
29
30type keyAlias struct {
31	name, key string
32}
33
34type Manager struct {
35	aliases []keyAlias
36}
37
38func (m *Manager) addAliases(aliases []string) (err error) {
39	for _, data := range aliases {
40		var name, key string
41		if name, key, err = itemutil.ParseAlias(data); err != nil {
42			return fmt.Errorf("cannot add alias \"%s\": %s", data, err)
43		}
44		for _, existingAlias := range m.aliases {
45			if existingAlias.name == name {
46				return fmt.Errorf("failed to add Alias \"%s\": duplicate name", name)
47			}
48		}
49		m.aliases = append(m.aliases, keyAlias{name: name, key: key})
50	}
51	return nil
52}
53
54func NewManager(options *agent.AgentOptions) (m *Manager, err error) {
55	m = &Manager{
56		aliases: make([]keyAlias, 0),
57	}
58	if options != nil {
59		if err = m.initialize(options); err != nil {
60			return nil, err
61		}
62	}
63	return
64}
65
66func (m *Manager) Get(orig string) string {
67	if _, _, err := itemutil.ParseKey(orig); err != nil {
68		return orig
69	}
70	for _, a := range m.aliases {
71		if strings.Compare(a.name, orig) == 0 {
72			return a.key
73		}
74	}
75	for _, a := range m.aliases {
76		aliasLn := len(a.name)
77		if aliasLn <= 3 || a.name[aliasLn-3:] != `[*]` {
78			continue
79		}
80		if aliasLn-2 > len(orig) {
81			return orig
82		}
83		if strings.Compare(a.name[:aliasLn-2], orig[:aliasLn-2]) != 0 {
84			continue
85		}
86		if len(a.key) <= 3 || a.key[len(a.key)-3:] != `[*]` {
87			return a.key
88		}
89		return string(a.key[:len(a.key)-3] + orig[len(a.name)-3:])
90	}
91	return orig
92}
93