#!/usr/bin/env python
#-
# Copyright (c) 2016 iXsystems, Inc.
# All rights reserved.
# This file is a part of TrueNAS
# and may not be copied and/or distributed
# without the express permission of iXsystems.

import json
import os
import sys

sys.path.append('/usr/local/www')
sys.path.append('/usr/local/www/freenasUI')

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'freenasUI.settings')

# Make sure to load all modules
from django.db.models.loading import cache
cache.get_apps()

from freenasUI.storage.models import Task, Replication

if len(sys.argv) != 3:
    sys.exit(1)

ssh_client_data = os.getenv("SSH_CLIENT")
remote, outport, inport = ssh_client_data.split(' ', 3)
remote_dataset = sys.argv[1]
local_dataset = sys.argv[2]

replication_tasks = Replication.objects.all()
snapshot_tasks = Task.objects.all()

related_snapshots = []
related_replications = []
output = []

for task in snapshot_tasks:
    if task.task_filesystem == local_dataset:
        related_snapshots.append(task)

for task in replication_tasks:
    if task.repl_filesystem == local_dataset and task.repl_zfs == remote_dataset and str(task.repl_remote) == remote:
        related_replications.append(task)

for task in related_snapshots:
    output.append({
        'type': 'snapshot',
        'dataset': task.task_filesystem,
        'recursive': task.task_recursive,
        'lifetime': task.task_ret_count,
        'lifetime_unit': task.task_ret_unit,
        'begin': str(task.task_begin),
        'end': str(task.task_end),
        'interval': task.task_interval,
        'interval_unit': task.task_repeat_unit,
        'days': task.task_byweekday,
        'enabled': task.task_enabled
    })

for task in related_replications:
    output.append({
        'type': 'replication',
        'dataset': task.repl_filesystem,
        'remote': {
            'user_enabled': task.repl_remote.ssh_remote_dedicateduser_enabled,
            'cipher': task.repl_remote.ssh_cipher,
        },
        'remote_dataset': task.repl_zfs,
        'recursive': task.repl_userepl,
        'followdelete': task.repl_followdelete,
        'compression': task.repl_compression,
        'limit': task.repl_limit,
        'begin': str(task.repl_begin),
        'end': str(task.repl_end),
        'enabled': task.repl_enabled
    })

sys.stdout.write(json.dumps(output, encoding='utf-8'))

for task in related_replications:
    task.delete()

for task in related_snapshots:
    task.delete()

sys.exit(0)
