#! /usr/bin/python
# $Header: https://oberon.oapd.inaf.it/shins/trunk/shins/src/scripts/simul.py 3920 2022-04-21 10:23:44Z depa $

import argparse
import subprocess
from util import variables as uvars


def config_file(device):
    component = uvars.devices[device]
    return uvars.base_path + component+"/"+component+"-svr.cfg"

    
def monit_service(device):
    component = uvars.devices[device]
    return component+"-svr"


def restart(services):
    if not isinstance(services, list):
        services = [services]

    for service in services:
        print("Wait some time for monit restart {}".format(service))
        subprocess.call("sudo monit restart {}".format(service), shell=True)
    

def is_commented(line):
    if uvars.comment_char in line.strip()[0] :
        return True
    else:
        return False

    
def is_sim(device):
    config = config_file(device)
    
    with open(config, 'r') as f:
        lines = f.readlines()
        for line in lines:
            if (device in line) and ("CONFIG" in line):
                return is_commented(line)

                
def toggle_comment(device):
    config = config_file(device)
    
    with open(config, 'r') as f:
        lines = f.readlines()
        for idx, line in enumerate(lines):
            if (device in line) and ("CONFIG" in line):
                if is_commented(line):
                    lines[idx] = line.replace("#","").strip()+"\n"
                else:
                    lines[idx] = "#"+line

    with open(config, 'w') as f:
        f.writelines(lines)

        
def toggle_sim(several_devices):
    if not isinstance(several_devices, list):
        several_devices = [several_devices]
        
    services = []
    for device in several_devices:
        service = monit_service(device)
        if not service in services:
            services.append(service)            
            
    for device in several_devices:
        toggle_comment(device)
        
    restart(services)
        

if __name__ == "__main__":
    
    parser = argparse.ArgumentParser(description="Toggle devices in sim and restart associated monit services")
    parser.add_argument(*["-l", "--list"], **{'action': 'store_true', 'help':"List device status"})
    parser.add_argument(*["-t", "--toggle"],  **{'type':str, 'nargs':'+', 'help': "toggle device sim status"})
    
    args = parser.parse_args()

    if args.list:
        for device in uvars.devices:
            print("{:15s} sim status: {}".format(device, is_sim(device)))

    if args.toggle:
        toggle_sim(args.toggle)
