server/init.py

170 lines
4.1 KiB
Python
Executable File

#!/usr/bin/python3
import os
import secrets
## A simple tool go generate an sql init script
# qconst sql="init.sql"
# cd priv
# seafile_user returns a sql command string to create seafile user and db
# def seafile_user():
# if 'SEAFILE_MYSQL_DB_USER' in#
# only allow aA-zZ, 0-9 and below "special" characters in passwords
ALLOWED_CHARS = [ord('!'), ord('@'), ord('#'), ord('%'), ord('&')]\
+ list(range(48,58))\
+ list(range(64,90))\
+ list(range(97,123))
# convert ints back to characters
ALLOWED_CHARS = [chr(c) for c in ALLOWED_CHARS]
def gen_pass(l):
"""
gen_pass returns a password of length l
:param l: is an integer that represents desired password length
"""
password = ""
for i in range(int(l)):
password += secrets.choice(ALLOWED_CHARS)
return password
def prompt_fill(key):
prompt = f"{key} was not set in config, please select an option below:\n"
prompt += f"\t1) leave blank (DEAFAULT)\n"
prompt += f"\t2) generate password\n"
prompt += f"\t3) enter value\n"
choice = input(prompt)
while choice not in "123":
print(f"error: {choice} unrecognized, please enter a number 1-3 or leave blank")
choice = input(prompt)
if choice == "1" or choice == "":
return ""
elif choice == "2":
return gen_pass(32)
elif choice == "3":
# run until user confirms input
user_input = ""
confirm = None
while confirm not in ["", "Y", "y"]:
user_input = input("please enter desired value:")
confirm = input(f"set {key} to {user_input} (Y/n)?")
return user_input
def sql_init(password):
sql = f"CREATE USER 'root'@'localhost' IDENTIFIED BY 'local';\n"
sql += f"GRANT ALL PRIVILEGES ON *.* TO 'root'@'%%';\n"
return sql
def sql_add_user(username, password, *databases):
sql = f"CREATE USER {username} IDENTIFIED BY '{password}';\n"
for db in databases:
sql += f"CREATE DATABASE {db};\n"
sql += f"GRANT ALL PRIVILEGES ON {db} TO {username};\n"
return sql
def parse_env(service):
"""
parse_env returns a dictionary of env vars parsed from the base file
:service: is a string of the service name to parse, must match folder name
"""
print(f"\nsetting up {service}...")
f = open(f"{service}/env")
c = dict()
for line in f:
# skip comments
if line[0] == "#":
continue
if line.isspace():
continue
kv = line.strip('\n').split("=")
key = kv[0]
val = kv[1].strip('"')
if val == "":
val = prompt_fill(key)
c[key] = val
return c
def gen_env(kv):
"""
gen_env takes in a dictionary and returns the formatted env file
:kv: is a dictionary of strings
"""
env = ""
for key, value in kv.items():
env += f"{key}=\"{value}\"\n"
return env
def service_init(service):
priv = f"{service}/.env"
sql = ""
# prevent overwrite
if os.path.isfile(priv):
print(f"{priv} already exists... skipping")
return sql
c = parse_env(service)
if service == "mariadb":
password = c["MYSQL_ROOT_PASSWORD"]
sql = sql_init(password)
elif service == "gitea":
username = c["GITEA__database__USER"]
password = c["GITEA__database__PASSWD"]
db = c["GITEA__database__NAME"]
sql = sql_add_user(username, password, db)
elif service == "seafile":
username = c["SEAFILE_MYSQL_DB_USER"]
password = c["SEAFILE_MYSQL_DB_PASSWORD"]
dbs = ["ccnet_db", "seafile_db", "seahub_db"]
sql = sql_add_user(username, password, *dbs)
else:
print(f"service {service} not regonized!")
os.exit(1)
env = gen_env(c)
f = open(priv, 'w')
f.write(env)
f.close()
return sql
sql=""
for service in ["mariadb", "gitea", "seafile"]:
sql += service_init(service)
# attempt to write sql init script based on parameters
if os.path.isfile("priv/init.sql"):
print("priv/init.sql already exists... skipping")
exit
f = open("priv/init.sql", 'w')
f.write(sql)
f.close()