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

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

def migrate_common_lib(values):
    delete_keys = [
        'service', 'updateStrategy', 'certificate', 'enableResourceLimits', 'cpuLimit',
        'memLimit', 'dnsConfig', 'environmentVariables', 'nextcloud', 'cronjob', 'nginx',
        'nginxConfig', 'postgresAppVolumeMounts', 'extraAppVolumeMounts', 'appVolumeMounts',
        'useServiceNameForHost',
    ]

    values.update({
        # Migrate Network
        'ncNetwork': {
            'webPort': values['service']['nodePort'],
            'certificateID': values['certificate'],
            'nginx': {
                'proxyTimeouts': values.get('nginxConfig', {}).get('proxy_timeouts', 60),
                'useDifferentAccessPort': values.get('nginxConfig', {}).get('useDifferentAccessPort', False),
                'externalAccessPort': values.get('nginxConfig', {}).get('externalAccessPort', 443)
            } if values['certificate'] else {}
        },
        # Migrate Resources
        'resources': {
            'limits': {
                'cpu': values.get('cpuLimit', '4000m'),
                'memory': values.get('memLimit', '8Gi'),
            }
        },
        # Migrate DNS
        'podOptions': {
            'dnsConfig': {
                'options': [
                    {'name': opt['name'], 'value': opt['value']}
                    for opt in values.get('dnsConfig', {}).get('options', [])
                ]
            }
        },
        # Migrate Config
        'ncConfig': {
            'additionalEnvs': values.get('environmentVariables', []),
            'adminUser': values['nextcloud']['username'],
            'adminPassword': values['nextcloud']['password'],
            'host': values['nextcloud'].get('host', ''),
            'dataDir': values['nextcloud']['datadir'],
            'commands': (['ffmpeg'] if values['nextcloud']['install_ffmpeg'] else []) + (['smbclient'] if values['nextcloud']['install_smbclient'] else []),
            'maxUploadLimit': values['nextcloud']['max_upload_size'],
            'maxExecutionTime': values['nextcloud']['max_execution_time'],
            'phpMemoryLimit': values['nextcloud']['php_memory_limit'],
            'opCacheMemoryConsumption': values['nextcloud']['opcache_memory_consumption'],
            'cron': {
                'enabled': values['cronjob']['enabled'],
                'schedule': values['cronjob']['schedule'] if values['cronjob']['enabled'] else '*/15 * * * *',
            }
        },
        # Migrate Storage
        'ncStorage': {
            'isDataInTheSameVolume': True,
            'pgData': migrate_volume(values['postgresAppVolumeMounts']['postgres-data']),
            'pgBackup': migrate_volume(values['postgresAppVolumeMounts']['postgres-backup']),
            'data': migrate_volume(values['appVolumeMounts']['nextcloud-data']),
            'html': migrate_volume(values['appVolumeMounts']['nextcloud-data']),
            'additionalStorages': [
                {
                    'type': 'hostPath',
                    'hostPathConfig': {'hostPath': e['hostPath']},
                    'mountPath': e['mountPath'],
                }
                for e in values.get('extraAppVolumeMounts', [])
            ],
        },
    })

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

    return values

def migrate(values):
    if 'isDataInTheSameVolume' in values.keys():
        values['ncStorage']['isDataInTheSameVolume'] = values.pop('isDataInTheSameVolume', True)
        return values

    # If this missing, we have already migrated
    if not 'appVolumeMounts' in values.keys():
        if 'certificateID' in values['ncNetwork']:
            if not values['ncNetwork']['certificateID']:
                values['ncNetwork']['nginx'] = {}
        # If 'shouldFixMigration' missing, we should fix migration and then add the key
        if not 'migrationFixed' in values['ncStorage'].keys():
            values['ncStorage']['isDataInTheSameVolume'] = True
            values['ncStorage']['migrationFixed'] = True
        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()))))
