1#include "unencrypted_properties.h"
2
3#include <sys/stat.h>
4#include <dirent.h>
5
6namespace properties {
7    const char* key = "key";
8    const char* ref = "ref";
9    const char* props = "props";
10    const char* is_default = "is_default";
11}
12
13namespace
14{
15    const char* unencrypted_folder = "unencrypted";
16}
17
18std::string UnencryptedProperties::GetPath(const char* device)
19{
20    return std::string() + device + "/" + unencrypted_folder;
21}
22
23UnencryptedProperties::UnencryptedProperties(const char* device)
24  : folder_(GetPath(device))
25{
26    DIR* dir = opendir(folder_.c_str());
27    if (dir) {
28        closedir(dir);
29    } else {
30        folder_.clear();
31    }
32}
33
34UnencryptedProperties::UnencryptedProperties()
35{
36}
37
38template<> std::string UnencryptedProperties::Get(const char* name,
39                                      std::string default_value) const
40{
41    if (!OK()) return default_value;
42    std::ifstream i(folder_ + "/" + name, std::ios::binary);
43    if (!i) {
44        return default_value;
45    }
46
47    i.seekg(0, std::ios::end);
48    int length = i.tellg();
49    i.seekg(0, std::ios::beg);
50    if (length == -1) {
51        return default_value;
52    }
53
54    std::string s(length, 0);
55    i.read(&s[0], length);
56    if (!i) {
57        return default_value;
58    }
59
60    return s;
61}
62
63template<> bool UnencryptedProperties::Set(const char* name, std::string const& value)
64{
65    if (!OK()) return false;
66    std::ofstream o(folder_ + "/" + name, std::ios::binary);
67    o << value;
68    return !o.fail();
69}
70
71UnencryptedProperties UnencryptedProperties::GetChild(const char* name) const
72{
73    UnencryptedProperties up;
74    if (!OK()) return up;
75
76    std::string directory(folder_ + "/" + name);
77    if (mkdir(directory.c_str(), 700) == -1 && errno != EEXIST) {
78        return up;
79    }
80
81    up.folder_ = directory;
82    return up;
83}
84
85bool UnencryptedProperties::Remove(const char* name)
86{
87    if (!OK()) return false;
88    if (remove((folder_ + "/" + name).c_str())
89        && errno != ENOENT) {
90        return false;
91    }
92
93    return true;
94}
95
96bool UnencryptedProperties::OK() const
97{
98    return !folder_.empty();
99}
100