import shutil
import os
import subprocess

def main():
    # Copy lighttpd.conf
    shutil.copy('/etc/lighttpd/lighttpd.conf', '/etc/lighttpd/lighttpd.conf.back')
    shutil.copy('/opt/opengnsys/lib/httpd/lighttpd.conf', '/etc/lighttpd/')

    # Copy 10-cgi.conf
    shutil.copy('/etc/lighttpd/conf-enabled/10-cgi.conf', '/etc/lighttpd/conf-enabled/10-cgi.conf.back')
    shutil.copy('/opt/opengnsys/lib/httpd/10-cgi.conf', '/etc/lighttpd/conf-enabled/')

    # Start lighttpd service
    subprocess.run(['/etc/init.d/lighttpd', 'start'])

    # Change permissions and create directories
    os.chmod('/opt', 0o755)
    os.makedirs('/usr/lib/cgi-bin', exist_ok=True)

    # Copy files to /usr/lib/cgi-bin
    for filename in os.listdir('/opt/opengnsys/lib/httpd/'):
        full_file_name = os.path.join('/opt/opengnsys/lib/httpd/', filename)
        if os.path.isfile(full_file_name):
            shutil.copy(full_file_name, '/usr/lib/cgi-bin')

    # Run dstat command
    with open('/tmp/bandwidth', 'w') as f:
        subprocess.Popen(['dstat', '-dn', '10'], stdout=f)

    # Append "WAITING" to OGLOGSESSION
    oglogsession = os.getenv('OGLOGSESSION')
    if oglogsession:
        with open(oglogsession, 'a') as f:
            f.write("WAITING\n")

if __name__ == "__main__":
    main()
