import sqlite3
import os

conn = sqlite3.connect('dockermanager/db/db.sqlite3')
cursor = conn.cursor()

cursor.execute("SELECT name FROM users_container")
containers = cursor.fetchall()

for container in containers:
    name = container[0]
    if(not os.path.exists("all_containers/"+name+".yml")):
        cursor.execute("SELECT login, password FROM users_container WHERE name='"+name+"'")
        up = cursor.fetchone()
        username = up[0]
        password = up[1]
        os.system(f"./scripts/new_container.sh {name} {username} {password}")

cursor.execute("SELECT name FROM users_container WHERE status='e' and expdate > datetime('now', 'localtime')")
enabled_containers = cursor.fetchall()

disabled_containers = list(set(containers) - set(enabled_containers))

for container in enabled_containers:
    name = container[0]
    os.system(f"./scripts/start_container.sh {name}")

for container in disabled_containers:
    name = container[0]
    cursor.execute("UPDATE users_container SET status = 'd' WHERE name = '"+name+"'")
    os.system(f"./scripts/stop_container.sh {name}")

os.system(f"./scripts/remove_deleted.sh")

conn.commit()
conn.close()