#!/var/lib/ecp-veil/node/env/bin/python3
"""
Script is intended to upgrade older UDP-based GFS2 clusters to SCTP during upgrade to SpaceVM 6.4
"""
from sys import exit
from os import path
from shutil import copy2

COROSYNC_CFG = '/etc/corosync/corosync.conf'
DLM_CFG = '/etc/dlm/dlm.conf'
BKUP_DIR = '/var/lib/ecp-veil/node/other/'
CR = '\n'

if not path.exists(COROSYNC_CFG):
    print('No corosync.conf found. Exiting.')
    exit(0)

if not path.exists(DLM_CFG):
    print('No dlm.conf found. Exiting.')
    exit(0)

with open(COROSYNC_CFG, 'r') as corosync:
    corosync_buff = corosync.read()
    splines = corosync_buff.splitlines()
    out = []
    if not ("transport: knet" in (lst := list(map(str.strip, splines)))
            and [l for l in lst if l.startswith('interface {')]):
        print('Old Corosync config (non-KNET or interface sections not found). Processing...')
        totem = False
        for line in splines:
            if not (lstr := line.strip()):
                continue
            if totem:
                if lstr == '}':
                    out += ['  interface {',
                            '    linknumber: 0',
                            '    knet_transport: sctp',
                            '    knet_link_priority: 1',
                            '  }',
                            '']
                    out.append(line)
                    totem = False
                elif lstr == 'transport: udpu':
                    out.append('  transport: knet')
                else:
                    out.append(line)
            else:
                if lstr.startswith('totem {'):
                    totem = True
                elif lstr == '}':
                    out += [line,'']
                else:
                    out.append(line)
    else:
        print('Corosync config is already KNET based.')

if out:
    print('Applying changes...')
    if not path.exists(corosync_bkup := path.join(BKUP_DIR, 'corosync_bkup.conf')):
        copy2(COROSYNC_CFG, corosync_bkup)
    with open(COROSYNC_CFG, 'w') as corosync_w:
        for line in out:
            corosync_w.write(line + '\n')
    print('Done. Corosync config is now KNET based.')


with open(DLM_CFG, 'r') as dlm:
    dlm_buff = dlm.read()
    lines = map(str.strip, [line for line in dlm_buff.splitlines()])
if 'protocol=sctp' not in lines:
    with open(DLM_CFG, 'a') as dlm:
        dlm.write(f'{"" if dlm_buff.endswith(CR) else CR}protocol=sctp\n')
    print('Done. DLM config is now SCTP based.')
else:
    print('DLM config is already SCTP based.')
