<script setup>

import { ref, onMounted, useTemplateRef, watchEffect } from 'vue';
import { Notification, Button, SingleSelect, FormGroup, PasswordInput, TextInput, Checkbox } from '@cloudron/pankow';
import { copyToClipboard } from '@cloudron/pankow/utils';
import { REGIONS_CONTABO, REGIONS_VULTR, REGIONS_IONOS, REGIONS_OVH, REGIONS_LINODE, REGIONS_SCALEWAY, REGIONS_WASABI } from '../constants.js';
import { redirectIfNeeded, mountlike, s3like, parseFullBackupPath } from  '../utils.js';
import ProvisionModel from '../models/ProvisionModel.js';
import BackupProviderForm from '../components/BackupProviderForm.vue';
import Whirlpool from '../components/Whirlpool.vue';
import AnimatedDots from '../components/AnimatedDots.vue';

const provisionModel = ProvisionModel.create();

const ipProviders = [
  { name: 'Disabled', value: 'noop' },
  { name: 'Public IP', value: 'generic' },
  { name: 'Static IP Address', value: 'fixed' },
  { name: 'Network Interface', value: 'network-interface' }
];

const formError = ref({});
const busy = ref(false);
const ready = ref(false);
const waitingForRestore = ref(false);
const progressMessage = ref('');
const taskMinutesActive = ref(0);
const provider = ref('');
const providerConfig = ref({});
const fullPath = ref('');
const format = ref('');
const encrypted = ref(false);
const encryptionPasswordHint = ref('');
const encryptionPassword = ref('');
const encryptedFilenames = ref(false);
const showAdvanced = ref(false);
const ipv4Provider = ref('generic');
const ipv4Address = ref('');
const ipv4Interface = ref('');
const ipv6Provider = ref('generic');
const ipv6Address = ref('');
const ipv6Interface = ref('');
const skipDnsSetup = ref(false);
const siteId = ref('');

const form = useTemplateRef('form');
const isFormValid = ref(false);
function checkValidity() {
  isFormValid.value = form.value ? form.value.checkValidity() : false;
}

async function waitForRestore () {
  waitingForRestore.value = true;
  formError.value = {};

  const [error, result] = await provisionModel.status();
  if (error) {
    setTimeout(waitForRestore, 5000);
    return console.error(error);
  }

  if (!result.restore.active) {
    if (result.adminFqdn && !result.restore.errorMessage) { // proceed to dashboard
      window.location.href = 'https://' + result.adminFqdn;
      return;
    }

    // restore reset or errored. start over
    formError.value.dnsWait = true;
    formError.value.generic = result.restore.errorMessage;
    waitingForRestore.value = false;
    busy.value = false;
    return;
  }

  progressMessage.value = result.restore.message;
  // TODO do we have the time here?
  taskMinutesActive.value = (new Date() - new Date(result.restore.startTime)) / 60000;

  setTimeout(waitForRestore, 5000);
}

async function onSubmit() {
  if (!form.value.reportValidity()) return;

  busy.value = true;
  formError.value = {};

  if (fullPath.value.indexOf('/') === -1) {
    formError.value.generic = 'Backup id must include the directory path';
    formError.value.remotePath = true;
    busy.value = false;
    return;
  }

  if (fullPath.value.indexOf('box') === -1) {
    formError.value.generic = 'Backup id must contain "box"';
    formError.value.remotePath = true;
    busy.value = false;
    return;
  }

  const version = fullPath.value.match(/_v(\d+.\d+.\d+)/);
  if (!version) {
    formError.value.generic = 'Backup id is missing version information';
    formError.value.remotePath = true;
    busy.value = false;
    return;
  }

  const config = {};
  const { prefix, remotePath } = parseFullBackupPath(fullPath.value);

  if (s3like(provider.value)) {
    config.endpoint = providerConfig.value.endpoint;
    config.prefix = prefix;
    config.bucket = providerConfig.value.bucket;
    config.accessKeyId = providerConfig.value.accessKeyId;
    config.secretAccessKey = providerConfig.value.secretAccessKey;

    if (provider.value === 's3') {
      config.region = providerConfig.value.region || undefined;
    } else if (provider.value === 'minio' || provider.value === 's3-v4-compat') {
      config.region = providerConfig.value.region || 'us-east-1';
      config.acceptSelfSignedCerts = providerConfig.value.acceptSelfSignedCerts;
      config.s3ForcePathStyle = true;
    } else if (provider.value === 'exoscale-sos') {
      config.region = 'us-east-1';
      config.signatureVersion = 'v4';
    } else if (provider.value === 'wasabi') {
      config.region = REGIONS_WASABI.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'scaleway-objectstorage') {
      config.region = REGIONS_SCALEWAY.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'linode-objectstorage') {
      config.region = REGIONS_LINODE.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'ovh-objectstorage') {
      config.region = REGIONS_OVH.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'ionos-objectstorage') {
      config.region = REGIONS_IONOS.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'vultr-objectstorage') {
      config.region = REGIONS_VULTR.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'contabo-objectstorage') {
      config.region = REGIONS_CONTABO.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
      config.s3ForcePathStyle = true;
    } else if (provider.value === 'upcloud-objectstorage') { // the UI sets region and endpoint
      const m = /^.*\.(.*)\.upcloudobjects.com$/.exec(config.endpoint);
      config.region = m ? m[1] : 'us-east-1'; // let it fail in validation phase if m is not valid
      config.signatureVersion = 'v4';
    } else if (provider.value === 'digitalocean-spaces') {
      config.region = 'us-east-1';
    } else if (provider.value === 'hetzner-objectstorage') {
      config.region = 'us-east-1';
      config.signatureVersion = 'v4';
    }
  } else if (mountlike(provider.value)) {
    config.prefix = prefix;
    // config.noHardlinks = !providerConfig.value.useHardlinks; // unused for restore
    config.mountOptions = {};

    if (provider.value === 'sshfs' || provider.value === 'cifs' || provider.value === 'nfs') {
      config.mountOptions.host = providerConfig.value.mountOptionHost;
      config.mountOptions.remoteDir = providerConfig.value.mountOptionRemoteDir;

      if (provider.value === 'cifs') {
        config.mountOptions.username = providerConfig.value.mountOptionUsername;
        config.mountOptions.password = providerConfig.value.mountOptionPassword;
        config.mountOptions.seal = !!providerConfig.value.mountOptionSeal;
        config.preserveAttributes = !!providerConfig.value.preserveAttributes;
      } else if (provider.value === 'sshfs') {
        config.mountOptions.user = providerConfig.value.mountOptionUser;
        config.mountOptions.port = parseInt(providerConfig.value.mountOptionPort);
        config.mountOptions.privateKey = providerConfig.value.mountOptionPrivateKey;
        config.preserveAttributes = true;
      }
    } else if (provider.value === 'ext4' || provider.value === 'xfs' || provider.value === 'disk') {
        config.mountOptions.diskPath = providerConfig.value.mountOptionDiskPath;
        config.preserveAttributes = true;
    } else if (provider.value === 'mountpoint') {
        config.mountPoint = providerConfig.value.mountPoint;
        config.chown = !!providerConfig.value.chown;
        config.preserveAttributes = !!providerConfig.value.preserveAttributes;
    }
  } else if (provider.value === 'filesystem') {
    config.backupDir = prefix;
    // unused for restore
    // config.noHardlinks = !providerConfig.value.useHardlinks;
    // config.preserveAttributes = true;
  } else if (provider.value === 'gcs') {
    config.bucket = providerConfig.value.bucket;
    config.prefix = prefix;
    config.projectId = providerConfig.value.projectId;
    config.credentials = providerConfig.value.credentials;
  }

  const data = {
    backupConfig: {
      provider: provider.value,
      config,
      format: format.value,
    },
    remotePath,
    version: version ? version[1] : '',
    ipv4Config: {
      provider: ipv4Provider.value,
      ip: ipv4Address.value,
      ifname: ipv4Interface.value,
    },
    ipv6Config: {
      provider: ipv6Provider.value,
      ip: ipv6Address.value,
      ifname: ipv6Interface.value,
    },
    skipDnsSetup: skipDnsSetup.value,
    siteId: siteId.value
  };

  if (encrypted.value) {
    data.backupConfig.encryptionPassword = encryptionPassword.value;
    data.backupConfig.encryptedFilenames = encryptedFilenames.value;
  }

  const [error] = await provisionModel.restore(data);
  if (error) {
    if (error.status === 424) {
      formError.value.generic = error.body.message;

      if (error.body.message.indexOf('AWS Access Key Id') !== -1) {
        formError.value.accessKeyId = true;
      } else if (error.body.message.indexOf('not match the signature') !== -1 ) {
        formError.value.secretAccessKey = true;
      } else if (error.body.message.toLowerCase() === 'access denied') {
        formError.value.bucket = true;
      } else if (error.body.message.indexOf('ECONNREFUSED') !== -1) {
        formError.value.generic = 'Unknown region';
        formError.value.region = true;
      } else if (error.body.message.toLowerCase() === 'wrong region') {
        formError.value.generic = 'Wrong S3 Region';
        formError.value.region = true;
      } else {
        formError.value.generic = error.body.message;
      }
    } else {
      formError.value.generic = error.body ? error.body.message : 'Internal error';
      console.error(error);
    }

    busy.value = false;
    return;
  }

  waitForRestore();
}

function onBackupConfigChanged(event) {
  const reader = new FileReader();
  reader.onload = function (result) {
    if (!result.target || !result.target.result) return console.error('Unable to read backup config');

    let data;
    try {
      data = JSON.parse(result.target.result); // 'provider', 'config', 'limits', 'format', 'remotePath', 'encrypted', 'encryptedFilenames'
      if (data.provider === 'filesystem') { // this allows a user to upload a backup to server and import easily with an absolute path
        data.remotePath = `${data.config.backupDir}/${data.remotePath}`;
      }
    } catch (e) {
      console.error('Unable to parse backup config', e);
      return;
    }

    provider.value = data.provider;
    fullPath.value = data.config.prefix ? `${data.config.prefix}/${data.remotePath}` : data.remotePath;
    format.value = data.format;
    encrypted.value = !!data.encrypted;
    encryptionPasswordHint.value = data.encryptionPasswordHint || '';
    encryptionPassword.value = '';
    encryptedFilenames.value = data.encryptedFilenames;
    siteId.value = data.siteId || '';

    providerConfig.value = {};
    for (const [key, value] of Object.entries(data.config)) {
      if (key === 'noHardlinks' || key === 'chown' || key === 'preserveAttributes') {
        // not really used for restoring
      } else if (key === 'mountOptions') { // providerConfig uses a flattened format of config.mountOptions
        providerConfig.value.mountOptionHost = data.config.mountOptions.host;
        providerConfig.value.mountOptionPort = data.config.mountOptions.port;
        providerConfig.value.mountOptionRemoteDir = data.config.mountOptions.remoteDir;
        providerConfig.value.mountOptionSeal = !!data.config.mountOptions.seal;
        providerConfig.value.mountOptionDiskPath = data.config.mountOptions.diskPath;
        providerConfig.value.mountOptionUser = data.config.mountOptions.user;
        providerConfig.value.mountOptionUsername = data.config.mountOptions.username;
        providerConfig.value.mountOptionPassword = data.config.mountOptions.password;
        providerConfig.value.mountOptionPrivateKey = '';
      } else {
        // s3: 'accessKeyId', 'secretAccessKey', 'bucket', 'prefix', 'signatureVersion', 'endpoint', 'region', 'acceptSelfSignedCerts', 's3ForcePathStyle'
        // gcs: 'bucket', 'prefix'
        providerConfig.value[key] = value;
      }
    }

    setTimeout(checkValidity, 100); // update state of the confirm button
  };

  reader.readAsText(event.target.files[0]);
}

const backupConfigFileInput = useTemplateRef('backupConfigFileInput');
function onUploadBackupConfig() {
  backupConfigFileInput.value.click();
}

function onCopyToClipboard(value) {
  copyToClipboard(value);
  window.pankow.notify('Copied');
}

watchEffect(() => {
  if (providerConfig.value.credentials) setTimeout(checkValidity, 100);
});

onMounted(async () => {
  const [error, status] = await provisionModel.status();
  if (error) return console.error(error);

  if (redirectIfNeeded(status, 'restore')) return; // redirected to some other view...

  const [error2, result] = await provisionModel.detectIp();
  if (error2) return console.error(error2);

  ipv4Provider.value = result.ipv4 ? 'generic' : 'noop';
  ipv6Provider.value = result.ipv6 ? 'generic' : 'noop';

  ready.value = true;

  if (status.restore.active) return waitForRestore();
  formError.value.generic = status.restore.errorMessage; // show any previous error
});

</script>

<template>
  <div class="container" v-if="ready">
    <Notification />

    <Transition name="fade-scale" mode="out-in">
      <div class="view" v-if="waitingForRestore" style="max-width: unset; height: 100%;">
        <div style="display: flex; flex-direction: column; height: 100%; align-items: center;">
          <Whirlpool/>
          <h1>Please wait while Cloudron is restoring <AnimatedDots/></h1>
          <h4 class="progress-message">{{ progressMessage }}</h4>
          <small>You can follow the logs on the server at <code @click="onCopyToClipboard('/home/yellowtent/platformdata/logs/box.log')">/home/yellowtent/platformdata/logs/box.log</code></small>
          <p v-show="taskMinutesActive >= 4">If restore appears stuck, it can be restarted by running <code @click="onCopyToClipboard('systemctl restart box')">systemctl restart box</code> and reloading this page.</p>
        </div>
      </div>

      <div class="view" v-else style="max-width: 500px;">
        <h1 style="text-align: center">Restore Cloudron</h1>
        <p>Provide the backup information to restore from, or
          <input type="file" ref="backupConfigFileInput" @change="onBackupConfigChanged" accept="application/json, text/json" style="display:none"/>
          <button type="button" style="background: none; border: none; color: #007bff; cursor: pointer; text-decoration: underline; padding: 0;" @click="onUploadBackupConfig()">
            upload a Backup Config
          </button>
        </p>

        <form ref="form" @submit.prevent="onSubmit()" @input="checkValidity()">
          <fieldset :disabled="busy">
            <input type="submit" style="display: none;"/>

            <!-- when provisioning=true BackupProviderForm won't display the error since we want to show the error above remotePath -->
            <div class="error-label" v-show="formError.generic">{{ formError.generic }}</div>

            <!-- remotePath contains the prefix as well -->
            <FormGroup>
              <label for="inputRemotePath">{{ $t('app.importBackupDialog.remotePath') }} <sup><a href="https://docs.cloudron.io/backups/#import-app-backup" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></label>
              <TextInput id="inputRemotePath" v-model="fullPath" required />
            </FormGroup>

            <BackupProviderForm ref="form"
              v-model:provider="provider"
              v-model:provider-config="providerConfig"
              v-model:format="format"
              :form-error="formError"
              :provisioning="true"
              :import-only="true" />

            <Checkbox v-model="encrypted" :label="$t('backups.configureBackupStorage.usesEncryption')"/>
            <FormGroup v-if="encrypted">
              <label for="encryptionPassswordInput">{{ $t('backups.configureBackupStorage.encryptionPassword') }}</label>
              <PasswordInput id="encryptionPassswordInput" v-model="encryptionPassword" :placeholder="$t('backups.configureBackupStorage.encryptionPasswordPlaceholder')" required/>
              <div class="warning-label" v-if="encryptionPasswordHint">{{ $t('backups.configureBackupStorage.encryptionHint') }}: {{ encryptionPasswordHint }}</div>
            </FormGroup>
            <Checkbox v-if="encrypted && format === 'rsync'" v-model="encryptedFilenames" :label="$t('backups.configureBackupStorage.encryptFilenames')"/>

            <div v-show="showAdvanced">
              <!-- IPv4 provider -->
              <FormGroup>
                <label class="control-label">IPv4 Configuration  <sup><a href="https://docs.cloudron.io/network/#ip-configuration" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></label>
                <SingleSelect v-model="ipv4Provider" :options="ipProviders" option-key="value" option-label="name" />
              </FormGroup>

              <!-- IPv4 Fixed -->
              <FormGroup v-if="ipv4Provider === 'fixed'">
                <label for="ipv4AddressInput">IPv4 Address</label>
                <TextInput id="ipv4AddressInput" v-model="ipv4Address" required />
              </FormGroup>

              <!-- IPv4 Network Interface -->
              <FormGroup v-if="ipv4Provider === 'network-interface'">
                <label for="ipv4InterfaceInput">IPv4 Interface Name</label>
                <TextInput id="ipv4InterfaceInput" v-model="ipv4Interface" required />
              </FormGroup>

              <!-- IPv6 provider -->
              <FormGroup>
                <label class="control-label">IPv6 Configuration  <sup><a href="https://docs.cloudron.io/networking/#ip-configuration" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></label>
                <SingleSelect v-model="ipv6Provider" :options="ipProviders" option-key="value" option-label="name" />
              </FormGroup>

              <!-- IPv6 Fixed -->
              <FormGroup v-if="ipv6Provider === 'fixed'">
                <label for="ipv6AddressInput">IPv6 Address</label>
                <TextInput id="ipv6AddressInput" v-model="ipv6Address" required />
              </FormGroup>

              <!-- IPv6 Network Interface -->
              <FormGroup v-if="ipv6Provider === 'network-interface'">
                <label for="ipv6InterfaceInpt">IPv6 Interface Name</label>
                <TextInput id="ipv6InterfaceInpt" v-model="ipv6Interface" required />
              </FormGroup>
            </div>

            <div class="actionable advanced" @click="showAdvanced = false" v-if="showAdvanced">Hide Advanced settings</div>
            <div class="actionable advanced" @click="showAdvanced = true" v-else>Advanced settings...</div>

            <div class="dry-run">
              <Checkbox v-model="skipDnsSetup" label="Dry run"/>
              <small class="helper-text">
                When enabled, apps are restored but the DNS records are not updated to point to this server.
                To access the dashboard, this browser's host must have an entry in <code>/etc/hosts</code> for the dashboard domain to this server's IP.
                See the <a href="https://docs.cloudron.io/backups/#dry-run-restore" target="_blank">docs</a> for more information.
              </small>
            </div>

          </fieldset>
        </form>

        <div class="actions">
          <Button @click="onSubmit()" :disabled="busy || !isFormValid" :loading="busy">Restore</Button>
          <a class="setup" href="/setup.html">Looking to setup?</a>
        </div>
      </div>
    </Transition>
  </div>
</template>

<style scoped>

.actions {
  margin-top: 1.5em;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.actions .setup {
  margin-top: 1em;
  font-size: 0.9em;
}

.advanced {
  margin-top: 20px;
}

.dry-run {
  margin-top: 20px;
}

.progress-message {
  margin-top: 0;
  max-width: 90vw;
  overflow: hidden;
  text-overflow: ellipsis;
}

</style>
