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


def migrate_volume(volume):
    return {
        'type': 'hostPath',
        'hostPathConfig': {
            'hostPath': volume['hostPath']
        },
    } if volume.get('hostPathEnabled', False) else {
        'type': 'ixVolume',
        'ixVolumeConfig': {
            'datasetName': volume['datasetName'],
        },
    }


def migrate_common_lib(values):
    delete_keys = [
        'web_port', 'timezone', 'dnsConfig', 'environmentVariables', 'ownerUID',
        'cronjobSchedule', 'diskoverCredentials', 'appVolumeMounts', 'ownerGID',
        'extraAppVolumeMounts', 'extraDataVolumeMounts', 'elasticSearchAppVolumeMounts',
        'elasticsearch', 'enableResourceLimits', 'es_user', 'python',
    ]

    additionalVols = [
        {
            'type': 'hostPath',
            'hostPathConfig': {'hostPath': e['hostPath']},
            'mountPath': e['mountPath'],
        } for e in values.get('extraAppVolumeMounts', [])
    ] + [
        {
            'type': 'hostPath',
            'hostPathConfig': {'hostPath': e['hostPath']},
            'mountPath': e['mountPath'],
            'diskoverDataIndex': True
        } for e in values.get('extraDataVolumeMounts', [])
    ]

    values.update({
        'TZ': values['timezone'],
        # Migrate Network
        'diskoverNetwork': {
            'webPort': values['web_port'],
        },
        # Migrate DNS
        'podOptions': {
            'dnsConfig': {
                'options': [
                    {'name': opt['name'], 'value': opt['value']}
                    for opt in values.get('dnsConfig', {}).get('options', [])
                ]
            }
        },
        # Migrate Resources
        'resources': {
            'limits': {
                'cpu': values.get('cpuLimit', '4000m'),
                'memory': values.get('memLimit', '8Gi'),
            }
        },
        # Migrate ID
        'diskoverID': {
            'user': values['ownerUID'],
            'group': values['ownerGID'],
        },
        # Migrate Config
        'diskoverConfig': {
            'cronSchedule': values['cronjobSchedule'],
            'username': values['diskoverCredentials']['username'],
            'password': values['diskoverCredentials']['password'],
            'additionalEnvs': values.get('environmentVariables', []),
        },
        # Migrate Storage
        'diskoverStorage': {
            'config': migrate_volume(values['appVolumeMounts']['config']),
            'data': migrate_volume(values['appVolumeMounts']['data']),
            'esdata': migrate_volume(values['elasticSearchAppVolumeMounts']['esdata']),
            'additionalStorages': additionalVols
        },
    })

    for k in delete_keys:
        values.pop(k, None)

    return values


def migrate(values):
    # Fix typo
    if 'discoverConfig' in values.keys():
        values['diskoverConfig'] = values.pop('discoverConfig')
    if 'discoverNetwork' in values.keys():
        values['diskoverNetwork'] = values.pop('discoverNetwork')
    if 'discoverStorage' in values.keys():
        values['diskoverStorage'] = values.pop('discoverStorage')
    # If this missing, we have already migrated
    if not 'appVolumeMounts' in values.keys():
        return values

    return migrate_common_lib(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()))))
