<?php

//******************************************************************************
//* Routes
//******************************************************************************
use DreamFactory\Enterprise\Database\Models\Snapshot;
\Route::any('/', ['uses' => 'HomeController@index']);
\Route::any('home', ['uses' => 'HomeController@index']);
\Route::post('status/{id}', ['uses' => 'HomeController@status']);
\Route::post('control/{id?}', ['uses' => 'HomeController@control']);
\Route::controllers(['auth' => 'Auth\\AuthController', 'password' => 'Auth\\PasswordController']);
/** Snapshot download handler */
\Route::get('/snapshot/{snapshotId}', function ($snapshotId) {
    return Snapshot::downloadFromHash($snapshotId);
});
/** Login event listener */
\Event::listen('auth.login', function () {
    \Auth::user()->update(['last_login_date' => date('c'), 'last_login_ip_text' => \Request::server('REMOTE_ADDR')]);
});
 /**
  * Given an instance and a snapshot ID, replace the data with that of the snapshot.
  *
  * @param int|string $instanceId
  * @param string     $snapshot A snapshot id or path to a snapshot
  *
  * @return array
  */
 public function restore($instanceId, $snapshot)
 {
     $_filename = null;
     $_instance = $this->_findInstance($instanceId);
     $snapshot = trim($snapshot, DIRECTORY_SEPARATOR . ' ');
     //  Determine source of import
     if (file_exists($snapshot)) {
         //  Absolute path
         $_filename = $snapshot;
     } else {
         if (file_exists($_instance->getSnapshotPath() . DIRECTORY_SEPARATOR . $snapshot)) {
             //  Relative to snapshot path
             $_filename = $_instance->getSnapshotPath() . DIRECTORY_SEPARATOR . $snapshot;
         } else {
             //  A snapshot hash given, find related snapshot
             /** @type Snapshot $_snapshot */
             if (null === ($_snapshot = Snapshot::with('route-hash')->bySnapshotId($snapshot)->first())) {
                 throw new \InvalidArgumentException('The snapshot "' . $snapshot . '" is unrecognized or invalid."');
             }
             return Provision::import(new ImportJob(new PortableServiceRequest($_instance, ['target' => $_snapshot->snapshot_id_text])));
         }
     }
     //  Mount the snapshot
     $_workPath = dirname($_filename);
     $_fsSnapshot = $this->mountSnapshot($instanceId, $_filename, $_workPath);
     //  Reconstitute the manifest and grab the services
     $_manifest = SnapshotManifest::createFromFile(config('snapshot.metadata-file-name'), $_fsSnapshot);
     $_services = Provision::getPortableServices($_manifest->get('guest-location'));
     $_result = [];
     foreach ($_fsSnapshot->listContents() as $_item) {
         //  Find the exports in the snapshot
         if (false !== ($_pos = stripos('-export.', $_item['file']))) {
             if (!PortableTypes::has($_type = substr($_item['file'], 0, $_pos))) {
                 continue;
             }
             if (array_key_exists($_type, $_services)) {
                 $_job = new ImportJob(new PortableServiceRequest($_instance, ['target' => $_workPath . DIRECTORY_SEPARATOR . $_item['file']]));
                 $_result[$_type] = $_services[$_type]->import($_job);
             }
         }
     }
     return $_result;
 }
 /**
  * @return array A list of available exports for this user
  */
 protected function getUserImportables()
 {
     $_result = [];
     /** @noinspection PhpUndefinedFieldInspection */
     $_rows = Snapshot::byUserId(\Auth::user()->id)->orderBy('create_date', 'desc')->get(['id', 'instance_id', 'snapshot_id_text']);
     if (!empty($_rows)) {
         /** @var Snapshot[] $_rows */
         foreach ($_rows as $_row) {
             list($_date, $_instanceName) = explode('.', $_row->snapshot_id_text, 2);
             try {
                 //  Find instance, dead or alive!
                 $_instance = $this->_locateInstance($_instanceName);
                 $_result[] = ['id' => $_row->id, 'name' => $_row->snapshot_id_text, 'instance-id' => $_instance ? $_instance->instance_id_text : 'unknown', 'export-date' => Carbon::create($_row->create_date)->toFormattedDateString(), 'instance-name' => $_instanceName];
             } catch (ModelNotFoundException $_ex) {
                 //  ignored on purpose
             }
         }
     }
     return $_result;
 }
 /**
  * @param string|int $snapshotId
  *
  * @return Snapshot|\Illuminate\Database\Eloquent\Model
  */
 protected static function findSnapshot($snapshotId)
 {
     return Snapshot::bySnapshotId($snapshotId)->with(['user', 'routeHash'])->firstOrFail();
 }