-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup
executable file
·302 lines (237 loc) · 10.4 KB
/
setup
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
#!/usr/bin/env python3
import time
import string
import random
import requests
import argparse
import os
import subprocess
import re
import glob
import sys
parser = argparse.ArgumentParser(description="Homeserver setup util")
subparsers = parser.add_subparsers(dest="command")
server_parser = subparsers.add_parser('server')
server_parser.add_argument("-r", "--run-server",
action="store_true", help="Start server")
server_parser.add_argument("--install-docker", action="store_true",help="Install docker engine.")
server_parser.add_argument("--hard-installation", action="store_true",
help="Remove docker engine before installation. Only RHEL&Debian based distros!")
config_parser = subparsers.add_parser('config')
config_parser.add_argument("-c", "--generate-certificates", action="store_true",
help="Set this value if you want SSL certificates to be generated, set it to 'False' or leave it blank if you want to use test certificates.")
config_parser.add_argument("--pass-certificate-arguments", action="store_true")
config_parser.add_argument("--random-env-passwds",action="store_true",help="Sets random passwd values.")
config_parser.add_argument("--default-env-files", action="store_true",
help="Set to 'True' if you want .env files to be created using standard instance files.")
config_parser.add_argument("-d", "--domain", type=str,
help="Set Nginx nameserver", required=False)
config_parser.add_argument("--upload-size", type=str,
help="File upload size limit, 0 is unlimited. Example: 16G, 100M.", required=False)
config_parser.add_argument("--nextcloud-subdomain", type=str, required=False,
help="nextcloud.example.com --> replaces nextcloud to any subdomain string")
config_parser.add_argument("-p", "--pull-images", action="store_true",
help="Pull docker images after configuration.")
backup_parser = subparsers.add_parser('backup')
backup_parser.add_argument("-a","--all",action="store_true")
backup_parser.add_argument("-n","--nextcloud",action="store_true")
backup_parser.add_argument("-of","--only-office",action="store_true")
backup_parser.add_argument('--dest',help="backup destination",required=False,default=None)
args = parser.parse_args()
def backup(full_backup:bool=False,nextcloud:bool=False,only_office:bool=False,destination=None):
volumes = {
"nextcloud":["nextcloud","db"],
"only-office":["onlyoffice-document-log","onlyoffice-document-data"]
}
def backup_script(destination:str,volume_name:str):
try:
os.makedirs(os.path.dirname(destination),exist_ok=True)
cmd = ["docker","run","--rm","-v",f"{os.path.abspath(os.path.dirname(destination))}:/backup",
"-v",f"{volume_name}:/volume","ubuntu","tar","cvf",f"/backup/{os.path.basename(destination)}"
,"/volume"]
subprocess.run(cmd,check=True)
print(f"Backup of volume '{volume_name}' completed successfully at '{destination}'.")
except subprocess.CalledProcessError as e:
print(f"Error during backup: {e}")
except Exception as e:
print(f"An unexpected error occured: {e}")
if destination == None: destination=os.getcwd()+"/backup"
if full_backup:
for key in volumes:
for volume in volumes[key]:
backup_script(destination,volume)
if nextcloud:
for volume in volumes["nextcloud"]:
backup_script(destination,volume)
if only_office:
for volume in volumes["only-office"]:
backup_script(destination,volume)
def check_pkg_manager():
managers = ["apt", "dnf", "yum", "zyper", "pacman"]
for manager in managers:
try:
output = subprocess.check_output(
["command", "-v", manager], text=True)
except:
print(manager+"packate manager is not competible")
return output
def remove_docker_engine():
pm = check_pkg_manager()
if "apt" in pm:
command = "for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do sudo apt-get remove $pkg; done"
subprocess.run(command, shell=True)
if pm in ["dnf", "yum"]:
command = "sudo dnf remove docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-selinux docker-engine-selinux docker-engine"
subprocess.run(command, shell=True)
def install_docker_engine():
installation_script_text = requests.get("https://get.docker.com").text
with open("/tmp/docker.sh", "w") as file:
file.write(installation_script_text)
subprocess.run("sudo bash /tmp/docker.sh", shell=True)
def pull_images():
cwd = os.getcwd()
subprocess.run("docker compose pull", cwd=cwd, shell=True)
def run_server():
cwd = os.getcwd()
subprocess.run("docker compose up -d", cwd=cwd, shell=True)
def generate_certificates(pass_certificate_arguments: bool):
cwd = os.getcwd()
if not os.path.exists(cwd+"/certs"):
os.makedirs(cwd+"certs")
command = "bash ../gencert"
if pass_certificate_arguments:
command = "yes NA |" + command
subprocess.run(command, shell=True, cwd=f"{cwd}/certs")
def default_env_files():
cwd = os.getcwd()
files = glob.glob(os.path.join(cwd, '**', 'example.env'), recursive=True)
for file in files:
new_file = os.path.join(os.path.dirname(file), '.env')
os.rename(file, new_file)
def set_domain(domain: str, nextcloud_subdomain: str = "nextcloud"):
cwd = os.getcwd()
if len(domain.split(".")) == 3:
domain = domain.split(".")[1]
elif len(domain.split(".")) == 2:
domain = domain.split(".")[0]
with open(f"{cwd}/nginx/nginx.conf", "r") as file:
lines = file.readlines()
with open(f"{cwd}/nginx/nginx.conf", "w") as file:
for line in lines:
if line.strip().startswith("server_name"):
rex = re.compile(
r"([\Sa-zA-Z1-9]+)\.([a-zA-Z1-9]+)\.([a-zA-Z1-9]+)")
domains = rex.findall(line)
for i in domains:
line = line.replace(f".{i[1]}.", f".{domain}.")
line = line.replace("nextcloud.", nextcloud_subdomain+".")
# line = re.sub(r'server_name\s+\S+;', f'server_name {domain};', line)
file.write(line)
with open(f"{cwd}/nextcloud/.env", "r") as file:
lines = file.readlines()
with open(f"{cwd}/nextcloud/.env", "w") as file:
for line in lines:
if line.strip().startswith("NEXTCLOUD_TRUSTED_DOMAINS"):
line = re.sub(r'NEXTCLOUD_TRUSTED_DOMAINS=.*',
f'NEXTCLOUD_TRUSTED_DOMAINS={nextcloud_subdomain}.{domain}')
file.write(line)
def set_upload_size(size: str):
cwd = os.getcwd()
files = ["/nextcloud/web/nginx.conf", "/nginx/conf.d/uploadsize.conf"]
for config_file in files:
with open(f"{cwd}{config_file}", "r") as file:
lines = file.readlines()
with open(f"{cwd}{config_file}", "w") as file:
for line in lines:
if line.strip().startswith("client_max_body_size"):
line = re.sub(r'client_max_body_size\s+\S+;',
f'client_max_body_size {size};', line)
file.write(line)
def generate_password(length=12):
if length < 4:
raise ValueError("Password lenght must longer than 4 char..")
# Büyük harf, küçük harf ve rakam karakterleri
upper = string.ascii_uppercase
lower = string.ascii_lowercase
digits = string.digits
# Şifrenin her bir bölümünden en az bir karakter ekleyelim
password = [
random.choice(upper),
random.choice(lower),
random.choice(digits)
]
# Geri kalan karakterleri rastgele seçelim
all_characters = upper + lower + digits
password += random.choices(all_characters, k=length - 4)
# Karakterleri karıştır
random.shuffle(password)
# Listeyi string'e çevir
return ''.join(password)
def random_env_passwds():
# MariaDB
db_root_passwd=generate_password()
db_passwd=generate_password()
nextcloud_admin_passwd=generate_password()
jwt_secret=generate_password()
# MariaDB
with open("./mariadb/.env","w") as file:
config = f"""MARIADB_ROOT_PASSWORD={db_root_passwd}
MYSQL_DATABASE=nextcloud
MYSQL_USER=nextcloud
MYSQL_PASSWORD={db_passwd}
"""
file.write(config)
# Nextcloud
with open("./nextcloud/.env","w") as file:
config = f"""MYSQL_DATABASE=nextcloud
MYSQL_USER=nextcloud
MYSQL_PASSWORD={db_passwd}
MYSQL_HOST=db
NEXTCLOUD_TRUSTED_DOMAINS=skycloud.yildizskylab.com cloud.yildizskylab.com
NEXTCLOUD_ADMIN_USER=nextcloud
NEXTCLOUD_ADMIN_PASSWORD={nextcloud_admin_passwd}
OVERWRITEPROTOCOL=https
"""
file.write(config)
# Only Office
with open("./nextcloud/only-office/.env","w") as file:
config = f"JWT_SECRET={jwt_secret}"
file.write(config)
if len(sys.argv) == 1:
parser.print_help()
sys.exit(0)
if args.command=="config":
if len(sys.argv) == 2:
config_parser.print_help()
sys.exit(0)
if args.generate_certificates:
generate_certificates(
pass_certificate_arguments=args.pass_certificate_arguments)
if args.default_env_files and not args.random_env_passwds:
default_env_files()
if args.random_env_passwds:
random_env_passwds()
if args.domain is not None:
if args.nextcloud_subdomain is not None:
set_domain(domain=args.domain, nextcloud_subdomain=args.nextcloud_subdomain)
else:
set_domain(domain=args.domain)
if args.upload_size is not None:
set_upload_size(size=args.upload_size)
if args.pull_images:
pull_images()
if args.command=="server":
if len(sys.argv) == 2:
server_parser.print_help()
sys.exit(0)
if args.install_docker:
if args.hard_installation:
remove_docker_engine()
install_docker_engine()
if args.run_server:
run_server()
if args.command=="backup":
if len(sys.argv) == 2:
backup_parser.print_help()
sys.exit(0)
backup(full_backup=args.all,nextcloud=args.nextcloud,only_office=args.only_office,destination=args.dest)