#!/usr/bin/python3
import json
import os
import sys


def storage_migrate(storage):
    delete_keys = []
    if storage['type'] == 'hostPath':
        # Check if the key exists, if not we have already migrated
        if not storage.get('hostPath'):
            return storage

        storage['hostPathConfig'] = {'hostPath': storage['hostPath']}
        delete_keys.append('hostPath')

    elif storage['type'] == 'ixVolume':
        # Check if the key exists, if not we have already migrated
        if not storage.get('datasetName'):
            return storage

        storage['ixVolumeConfig'] = {'datasetName': storage['datasetName']}
        delete_keys.append('datasetName')

    elif storage['type'] == 'smb-pv-pvc':
        # Check if the key exists, if not we have already migrated
        if not storage.get('server'):
            return storage

        storage['smbConfig'] = {
            'server': storage['server'],
            'share': storage['share'],
            'domain': storage['domain'],
            'username': storage['username'],
            'password': storage['password'],
            'size': storage['size'],
        }
        delete_keys.extend(['server', 'share', 'domain', 'username', 'password', 'size'])

    for key in delete_keys:
        storage.pop(key, None)

    return storage


def migrate(values):
    storage_key = 'sftpgoStorage'
    storages = ['config', 'data', 'backups']

    for storage in storages:
        check_val = values.get(storage_key, {}).get(storage, {})
        if not isinstance(check_val, dict) or not check_val:
            raise Exception(f'Storage section {storage} is malformed')

        values[storage_key][storage] = storage_migrate(check_val)

    additionalStorages = values.get(storage_key, {}).get('additionalStorages', [])
    for idx, storage in enumerate(additionalStorages):
        if not isinstance(storage, dict) or not storage:
            raise Exception(f'Item {idx} in additionalStorages is malformed')

        values[storage_key]['additionalStorages'][idx] = storage_migrate(storage)

    return values


if __name__ == '__main__':
    if len(sys.argv) != 2:
        exit(1)

    if os.path.exists(sys.argv[1]):
        with open(sys.argv[1], 'r') as f:
            print(json.dumps(migrate(json.loads(f.read()))))
