#!/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 logging
import libzfs
import sys

logging.basicConfig()
log = logging.getLogger('tools.set_dataset_readonly')

if len(sys.argv) not in [3, 4]:
    log.error('Invalid number of arguments provided. Valid arguments list is: dataset name <name> readonly value <on/off> recursive <yes/no>')
    sys.exit(1)

dataset_name = sys.argv[1]
set_state = sys.argv[2]
recursive = sys.argv[3] if len(sys.argv) == 4 else 'no'

if set_state not in ['on', 'off']:
    log.error('Invalid value {0} of readonly parameter selected. Proper values are: on/off'.format(set_state))

if recursive not in ['yes', 'no']:
    log.error('Invalid value {0} of recursive parameter selected. Proper values are: yes/no'.format(recursive))

related_datasets = []

try:
    zfs = libzfs.ZFS()
    for dataset in zfs.datasets:
        pool = dataset.name.split('/')[0]

        if recursive:
            if dataset_name not in dataset.name:
                continue
        else:
            if dataset_name != dataset.name:
                continue

        if '.system' in dataset.name:
            continue

        related_datasets.append(dataset)

        if 'readonly' in dataset.properties:
            dataset.properties['readonly'].value = set_state
        else:
            prop = libzfs.ZFSUserProperty(set_state)
            dataset.properties['readonly'] = prop
except libzfs.ZFSException as err:
    log.error('Readonly property set on {0} to value {1} failed: {2}'.format(dataset_name, set_state, err.message))
    sys.exit(1)

if len(related_datasets) == 0:
    log.error('Pool {0} does not exist'.format(dataset_name))

if set_state == 'off':
    related_datasets = sorted(related_datasets, key=lambda d: d.name)
    for dataset in related_datasets:
        if dataset.mountpoint:
            continue
        try:
            dataset.mount()
        except libzfs.ZFSException as err:
            log.error('Dataset {0} mount failed: {1}'.format(dataset.name, err.message))
            sys.exit(1)

sys.exit(0)
