<?php

App::uses('AppShell', 'Console/Command');

/**
 * Use:
 * $ cd {SITE_FOLDER}/app
 * $ ./Console/cake reset_acl
 */
class ResetAclShell extends AppShell {

    public $uses = array('User', 'Aro', 'Aco', 'ArosAco', 'Role');

    public function main() {

        $this->Aro->deleteAll(array('id > ' => '0'), true);
        $this->Aro->query('DELETE FROM aros_acos');

        $this->out('Tabelas Aros e ArosAcos Limpas');

        $acos = $this->Aco->find('all');
        $roles = $this->Role->find('all');
        foreach ($roles as $role) {

            $this->Aro->create();
            $aro = $this->Aro->save(array(
                'model' => 'Role',
                'foreign_key' => $role['Role']['id'],
                'alias' => $role['Role']['alias'],
                'parent' => 'parent_ARO_alias'
            ));

            if ($role['Role']['alias'] == 'admin') {
                foreach ($acos as $aco) {
                    $this->ArosAco->create();
                    $this->ArosAco->save(array(
                        '_create' => '1',
                        '_delete' => '1',
                        '_read' => '1',
                        '_update' => '1',
                        'aco_id' => $aco['Aco']['id'],
                        'aro_id' => $aro['Aro']['id'],
                    ));
                }
                $this->out('     Permissões para Role Admin Criadas');
            }
            else {
                foreach ($acos as $aco) {
                    $this->ArosAco->create();
                    $this->ArosAco->save(array(
                        '_create' => '0',
                        '_delete' => '0',
                        '_read' => '0',
                        '_update' => '0',
                        'aco_id' => $aco['Aco']['id'],
                        'aro_id' => $aro['Aro']['id'],
                    ));
                }

                $this->out("     Permissões para Role {$role['Role']['alias']} Criadas");
            }
        }

        $users = $this->User->find('all');
        foreach ($users as $user) {
            $this->Aro->create();
            $aro = $this->Aro->save(array(
                'model' => 'User',
                'foreign_key' => $user['User']['id'],
                'alias' => $user['User']['name'],
                'parent' => 'parent_ARO_alias'
            ));
            foreach ($acos as $aco) {
                $this->ArosAco->create();
                $this->ArosAco->save(array(
                    '_create' => '0',
                    '_delete' => '0',
                    '_read' => '0',
                    '_update' => '0',
                    'aco_id' => $aco['Aco']['id'],
                    'aro_id' => $aro['Aro']['id'],
                ));

            }
            $this->out("     Permissões para User {$user['User']['name']} Criadas");
        }

        $this->out('Done');
    }

}
