# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-27 21:42


from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import freenasUI.account.models
import freenasUI.freeadmin.models.fields
from freenasUI import choices
import json
import os


def create_builtin(apps, schema_editor):

    bsdGroups = apps.get_model('account', 'bsdGroups')
    bsdUsers = apps.get_model('account', 'bsdUsers')
    bsdGroupMembership = apps.get_model('account', 'bsdGroupMembership')

    jf = os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "fixtures", "bsdGroups.json")
    with open(jf) as json_fd:
        data = json_fd.read()
    groups = json.loads(data)
    for entry in groups:
        group = bsdGroups(pk=entry['pk'])
        for field in entry['fields']:
            mfield = bsdGroups._meta.get_field(field)
            setattr(group, field, entry['fields'].get(field))
        group.save()

    jf = os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "fixtures", "bsdUsers.json")
    with open(jf) as json_fd:
        data = json_fd.read()
    users = json.loads(data)
    for entry in users:
        user = bsdUsers(pk=entry['pk'])
        for field in entry['fields']:
            mfield = bsdUsers._meta.get_field(field)
            if mfield.rel is not None:
                inst = mfield.rel.to.objects.get(pk=entry['fields'].get(field))
                setattr(user, field, inst)
            else:
                setattr(user, field, entry['fields'].get(field))
        user.save()

    jf = os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "fixtures", "bsdGroupMembership.json")
    with open(jf) as json_fd:
        data = json_fd.read()
    members = json.loads(data)
    for entry in members:
        fields = entry['fields']
        group = bsdGroups.objects.get(pk=fields['bsdgrpmember_group'])
        user = bsdUsers.objects.get(pk=fields['bsdgrpmember_user'])
        membership = bsdGroupMembership(
            bsdgrpmember_group=group,
            bsdgrpmember_user=user,
        )
        membership.save()



class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='bsdUsers',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('bsdusr_uid', models.IntegerField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(4294967295)], verbose_name='User ID')),
                ('bsdusr_username', models.CharField(default='User &', max_length=16, unique=True, verbose_name='Username')),
                ('bsdusr_unixhash', models.CharField(blank=True, default='*', max_length=128, verbose_name='Hashed UNIX password')),
                ('bsdusr_smbhash', models.CharField(blank=True, default='*', max_length=128, verbose_name='Hashed SMB password')),
                ('bsdusr_home', freenasUI.freeadmin.models.fields.PathField(default='/nonexistent', max_length=255, verbose_name='Home Directory')),
                ('bsdusr_shell', models.CharField(choices=choices.SHELL_CHOICES(), default='/bin/csh', max_length=120, verbose_name='Shell')),
                ('bsdusr_full_name', models.CharField(max_length=120, verbose_name='Full Name')),
                ('bsdusr_builtin', models.BooleanField(default=False, editable=False, verbose_name='Built-in User')),
                ('bsdusr_email', models.EmailField(blank=True, max_length=254, verbose_name='E-mail')),
                ('bsdusr_password_disabled', models.BooleanField(default=False, help_text='This disables all forms of password login, including for sharing.', verbose_name='Disable password login')),
                ('bsdusr_locked', models.BooleanField(default=False, verbose_name='Lock user')),
                ('bsdusr_sudo', models.BooleanField(default=False, verbose_name='Permit Sudo')),
                ('bsdusr_microsoft_account', models.BooleanField(default=False, verbose_name='Microsoft Account')),
            ],
            options={
                'ordering': ['bsdusr_builtin', 'bsdusr_username'],
                'verbose_name': 'User',
                'verbose_name_plural': 'Users',
            },
        ),
        migrations.CreateModel(
            name='bsdGroupMembership',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ],
            options={
                'verbose_name': 'Group Membership',
                'verbose_name_plural': 'Group Memberships',
            },
        ),
        migrations.CreateModel(
            name='bsdGroups',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('bsdgrp_gid', models.IntegerField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(4294967295)], verbose_name='Group ID')),
                ('bsdgrp_group', models.CharField(max_length=120, unique=True, verbose_name='Group Name')),
                ('bsdgrp_builtin', models.BooleanField(default=False, editable=False, verbose_name='Built-in Group')),
                ('bsdgrp_sudo', models.BooleanField(default=False, verbose_name='Permit Sudo')),
            ],
            options={
                'ordering': ['bsdgrp_builtin', 'bsdgrp_group'],
                'verbose_name': 'Group',
                'verbose_name_plural': 'Groups',
            },
        ),
        migrations.AddField(
            model_name='bsdgroupmembership',
            name='bsdgrpmember_group',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='account.bsdGroups', verbose_name='Group'),
        ),
        migrations.AddField(
            model_name='bsdgroupmembership',
            name='bsdgrpmember_user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='User'),
        ),
        migrations.AddField(
            model_name='bsdusers',
            name='bsdusr_group',
            field=models.ForeignKey(on_delete=models.SET(freenasUI.account.models.get_sentinel_group), to='account.bsdGroups', verbose_name='Primary Group ID'),
        ),
        migrations.RunPython(create_builtin),
    ]
