<script setup>

import { ref, onMounted, watch, watchEffect } from 'vue';
import { Button, InputGroup, SingleSelect, FormGroup, TextInput, Checkbox, PasswordInput, NumberInput } from '@cloudron/pankow';
import { BACKUP_FORMATS, STORAGE_PROVIDERS, REGIONS_CONTABO, REGIONS_VULTR, REGIONS_IONOS, REGIONS_OVH, REGIONS_LINODE, REGIONS_SCALEWAY, REGIONS_EXOSCALE, REGIONS_DIGITALOCEAN, REGIONS_HETZNER, REGIONS_WASABI, REGIONS_S3 } from '../constants.js';
import ProvisionModel from '../models/ProvisionModel.js';
import SystemModel from '../models/SystemModel.js';
import { mountlike, s3like } from  '../utils.js';

const provider = defineModel('provider');
const providerConfig = defineModel('providerConfig');
const format = defineModel('format');

const props = defineProps({
  formError: {},
  importOnly: {
    type: Boolean,
    default: false,
  },
  provisioning: {
    type: Boolean,
    default: false,
  },
});

const systemModel = SystemModel.create();
const provisionModel = ProvisionModel.create();

const storageProviders = Array.from(STORAGE_PROVIDERS);
const ext4BlockDevices = ref([]);
const xfsBlockDevices = ref([]);
const gcsKeyFileName = ref('');
const gcsFileParseError = ref('');

function onGcsKeyChange(event) {
  gcsFileParseError.value = '';

  const fr = new FileReader();

  fr.onload = () => {
    // validate input file
    try {
      const keyJson = JSON.parse(fr.result);
      if (!keyJson.project_id) throw new Error('project_id field missing in JSON key file');
      if (!keyJson.client_email) throw new Error('client_email field missing in JSON key file');
      if (!keyJson.private_key) throw new Error('private_key field missing in JSON key file');

      providerConfig.value.projectId = keyJson.project_id;
      providerConfig.value.credentials = {
        client_email: keyJson.client_email,
        private_key: keyJson.private_key,
      };
    } catch (e) {
      if (e.name === 'SyntaxError') gcsFileParseError.value = 'Invalid JSON';
      else gcsFileParseError.value = e.message;

      providerConfig.value.projectId = '';
      providerConfig.value.credentials = {
        client_email: '',
        private_key: '',
      };
    }
  };
  fr.readAsText(event.target.files[0]);

  gcsKeyFileName.value = event.target.files[0].name;
}

async function getBlockDevices() {
  let error, blockDevices;

  if (props.provisioning) [error, blockDevices] = await provisionModel.blockDevices();
  else [error, blockDevices] = await systemModel.blockDevices();

  if (error) return console.error(error);

  ext4BlockDevices.value = [];
  xfsBlockDevices.value = [];
  for (const blockDevice of blockDevices) {
    if (blockDevice.mountpoints.some((mountpoint) => mountpoint === '/' || mountpoint.startsWith('/home') || mountpoint.startsWith('/boot'))) continue;
    blockDevice.label = blockDevice.path; // // amend label for UI
    if (blockDevice.type === 'ext4') ext4BlockDevices.value.push(blockDevice);
    else if (blockDevice.type === 'xfs') xfsBlockDevices.value.push(blockDevice);
  }
}

watch(provider, (newProvider) => {
  if (newProvider === 'scaleway-objectstorage') {
    // scaleway only supports 1000 parts per object (https://www.scaleway.com/en/docs/s3-multipart-upload/)
    if (parseInt(providerConfig.value.uploadPartSize) < 100 * 1024 * 1024) providerConfig.value.uploadPartSize = 100 * 1024 * 1024;
  } else if (newProvider === 's3') {
    if (parseInt(providerConfig.value.downloadConcurrency) < 30) providerConfig.value.downloadConcurrency = 30;
    if (parseInt(providerConfig.value.syncConcurrency) < 20) providerConfig.value.syncConcurrency = 20;
    if (parseInt(providerConfig.value.copyConcurrency) < 500) providerConfig.value.downloadConcurrency = 500;
  } else if (newProvider === 'cifs') {
    providerConfig.value.mountOptionSeal = true;
  } else if (newProvider === 'sshfs') {
    providerConfig.value.mountOptionPort = 23;
  } else if (newProvider === 'gcs') {
    providerConfig.value.credentials = {
      client_email: '',
      private_key: '',
    };
  }
});

watch(format, (newFormat) => {
  if (newFormat === 'rsync') {
    if (provider.value === 'filesystem' || mountlike(provider.value)) providerConfig.value.useHardlinks = true;
  }
});

watchEffect(() => {
  if (!providerConfig.value.mountOptionPrivateKey) return;
  providerConfig.value.mountOptionPrivateKey = providerConfig.value.mountOptionPrivateKey.replaceAll('\\n', '\n');
});

onMounted(async () => {
  await getBlockDevices();
});

</script>

<template>
  <div>
    <!-- when provisioning, the error has to be shown on top of the backup path in the view itself -->
    <div class="error-label" v-if="!provisioning && formError.generic">{{ formError.generic }}</div>

    <FormGroup>
      <label for="providerInput">{{ $t('backups.configureBackupStorage.provider') }} <sup><a href="https://docs.cloudron.io/backups/#storage-providers" class="help" target="_blank" tabindex="-1"><i class="fa fa-question-circle"></i></a></sup></label>
      <SingleSelect id="providerInput" v-model="provider" :options="storageProviders" option-key="value" option-label="name" required />
    </FormGroup>

    <!-- mountpoint -->
    <FormGroup v-if="provider === 'mountpoint'">
      <label for="mountPointInput">{{ $t('backups.configureBackupStorage.mountPoint') }}</label>
      <TextInput id="mountPointInput" v-model="providerConfig.mountPoint" placeholder="/mnt/backups" required/>
      <small class="helper-text" v-html="$t('backups.configureBackupStorage.mountPointDescription', { providerDocsLink: `https://docs.cloudron.io/backups/#${provider}` })"></small>
    </FormGroup>

    <!-- CIFS/NFS/SSHFS -->
    <FormGroup v-if="provider === 'cifs' || provider === 'nfs' || provider === 'sshfs'">
      <label for="mountOptionHostInput">{{ $t('backups.configureBackupStorage.server') }}</label>
      <TextInput id="mountOptionHostInput" v-model="providerConfig.mountOptionHost" placeholder="Server IP or hostname" required />
    </FormGroup>

    <!-- CIFS/NFS/SSHFS -->
    <FormGroup v-if="provider === 'cifs' || provider === 'nfs' || provider === 'sshfs'">
      <label for="mountOptionRemoteDirInput">{{ $t('backups.configureBackupStorage.remoteDirectory') }}</label>
      <TextInput id="mountOptionRemoteDirInput" v-model="providerConfig.mountOptionRemoteDir" placeholder="/share" required />
    </FormGroup>

    <!-- CIFS -->
    <Checkbox v-if="provider === 'cifs'" v-model="providerConfig.mountOptionSeal" :label="$t('backups.configureBackupStorage.cifsSealSupport')" />

    <!-- CIFS -->
    <FormGroup v-if="provider === 'cifs'">
      <label for="mountOptionUsernameInput">{{ $t('backups.configureBackupStorage.username') }}</label>
      <TextInput id="mountOptionUsernameInput" v-model="providerConfig.mountOptionUsername" required />
    </FormGroup>

    <!-- CIFS -->
    <FormGroup v-if="provider === 'cifs'">
      <label for="mountOptionPasswordInput">{{ $t('backups.configureBackupStorage.password') }}</label>
      <PasswordInput id="mountOptionPasswordInput" v-model="providerConfig.mountOptionPassword" required />
    </FormGroup>

    <!-- EXT4/XFS -->
    <FormGroup v-if="provider === 'xfs' || provider === 'ext4'">
      <label for="blockDevicePath">{{ $t('backups.configureBackupStorage.diskPath') }}</label>
      <SingleSelect id="blockDevicePath" v-if="provider === 'ext4'" v-model="providerConfig.mountOptionDiskPath" :options="ext4BlockDevices" option-label="label" option-key="path"/>
      <SingleSelect id="blockDevicePath" v-if="provider === 'xfs'" v-model="providerConfig.mountOptionDiskPath" :options="xfsBlockDevices" option-label="label" option-key="path"/>
    </FormGroup>

      <!-- Disk -->
    <FormGroup v-if="provider === 'disk'">
      <label class="control-label">{{ $t('backups.configureBackupStorage.diskPath') }}</label>
      <TextInput id="mountOptionDiskPathInput" v-model="providerConfig.mountOptionDiskPath" placeholder="/dev/disk/by-uuid/uuid" required />
    </FormGroup>

    <!-- SSHFS -->
    <FormGroup v-if="provider === 'sshfs'">
      <label for="mountOptionPortInput">{{ $t('backups.configureBackupStorage.port') }}</label>
      <NumberInput v-model="providerConfig.mountOptionPort" id="mountOptionPortInput" required />
    </FormGroup>

    <!-- SSHFS -->
    <FormGroup v-if="provider === 'sshfs'">
      <label for="mountOptionUserInput">{{ $t('backups.configureBackupStorage.user') }}</label>
      <TextInput id="mountOptionUserInput" v-model="providerConfig.mountOptionUser" required />
    </FormGroup>

    <!-- SSHFS -->
    <FormGroup v-if="provider === 'sshfs'">
      <label for="mountOptionPrivateKeyInput">{{ $t('backups.configureBackupStorage.privateKey') }}</label>
      <textarea id="mountOptionPrivateKeyInput" rows="7" style="white-space: nowrap;" v-model="providerConfig.mountOptionPrivateKey" required></textarea>
    </FormGroup>

    <!-- Filesystem -->
    <FormGroup v-if="provider === 'filesystem' && !importOnly">
      <label for="backupDirInput">{{ $t('backups.configureBackupStorage.localDirectory') }}</label>
      <TextInput id="backupDirInput" v-model="providerConfig.backupDir" placeholder="/opt/backups" required />
    </FormGroup>

    <!-- Endpoint - S3/Minio/SOS/GCS/UpCloud/B2/R2/C2 -->
    <FormGroup v-if="provider === 'minio' || provider === 'upcloud-objectstorage' || provider === 'backblaze-b2' || provider === 'cloudflare-r2' || provider === 's3-v4-compat' || provider === 'idrive-e2' || provider === 'synology-c2-objectstorage'">
      <label for="endpointInput">{{ $t('backups.configureBackupStorage.s3Endpoint') }}</label>
      <TextInput id="endpointInput" v-model="providerConfig.endpoint" placeholder="https://s3endpoint.example.com" required />
    </FormGroup>

    <Checkbox v-if="provider === 'minio' || provider === 's3-v4-compat'" v-model="providerConfig.acceptSelfSignedCerts" :label="$t('backups.configureBackupStorage.acceptSelfSignedCerts')"/>

    <FormGroup v-if="s3like(provider) || provider === 'gcs'">
      <label for="bucketInput">{{ $t('backups.configureBackupStorage.bucketName') }}</label>
      <TextInput id="bucketInput" v-model="providerConfig.bucket" required />
    </FormGroup>

    <!-- when importing/restoring, the user enters a fullPath which contains the prefix -->
    <FormGroup v-if="provider !== 'filesystem' && !importOnly">
      <label for="prefixInput">{{ $t('backups.configureBackupStorage.prefix') }}</label>
      <TextInput id="prefixInput" v-model="providerConfig.prefix" placeholder="my-backups" />
      <small class="helper-text">{{ $t('backups.configureBackupStorage.prefixHelperText') }}</small>
    </FormGroup>

    <!-- Region Selector -->
    <FormGroup v-if="
      provider === 's3' ||
      provider === 'digitalocean-spaces' ||
      provider === 'hetzner-objectstorage' ||
      provider === 'wasabi' ||
      provider === 'scaleway-objectstorage' ||
      provider === 'linode-objectstorage' ||
      provider === 'ovh-objectstorage' ||
      provider === 'ionos-objectstorage' ||
      provider === 'vultr-objectstorage' ||
      provider === 'contabo-objectstorage' ||
      provider === 'exoscale-sos'
      "
     >
      <label for="regionInput">{{ $t('backups.configureBackupStorage.region') }}</label>
      <SingleSelect id="regionInput" v-if="provider === 's3'" v-model="providerConfig.region" :options="REGIONS_S3" option-label="name" option-key="value" required />
      <SingleSelect id="regionInput" v-if="provider === 'digitalocean-spaces'" v-model="providerConfig.endpoint" :options="REGIONS_DIGITALOCEAN" option-label="name" option-key="value" required />
      <SingleSelect id="regionInput" v-if="provider === 'hetzner-objectstorage'" v-model="providerConfig.endpoint" :options="REGIONS_HETZNER" option-label="name" option-key="value" required />
      <SingleSelect id="regionInput" v-if="provider === 'exoscale-sos'" v-model="providerConfig.endpoint" :options="REGIONS_EXOSCALE" option-label="name" option-key="value" required />
      <SingleSelect id="regionInput" v-if="provider === 'wasabi'" v-model="providerConfig.endpoint" :options="REGIONS_WASABI" option-label="name" option-key="value" required />
      <SingleSelect id="regionInput" v-if="provider === 'scaleway-objectstorage'" v-model="providerConfig.endpoint" :options="REGIONS_SCALEWAY" option-label="name" option-key="value" required />
      <SingleSelect id="regionInput" v-if="provider === 'linode-objectstorage'" v-model="providerConfig.endpoint" :options="REGIONS_LINODE" option-label="name" option-key="value" required />
      <SingleSelect id="regionInput" v-if="provider === 'ovh-objectstorage'" v-model="providerConfig.endpoint" :options="REGIONS_OVH" option-label="name" option-key="value" required />
      <SingleSelect id="regionInput" v-if="provider === 'ionos-objectstorage'" v-model="providerConfig.endpoint" :options="REGIONS_IONOS" option-label="name" option-key="value" required />
      <SingleSelect id="regionInput" v-if="provider === 'vultr-objectstorage'" v-model="providerConfig.endpoint" :options="REGIONS_VULTR" option-label="name" option-key="value" required />
      <SingleSelect id="regionInput" v-if="provider === 'contabo-objectstorage'" v-model="providerConfig.endpoint" :options="REGIONS_CONTABO" option-label="name" option-key="value" required />
    </FormGroup>

    <FormGroup v-if="provider === 's3-v4-compat'">
      <label for="s3v4CompatRegionInput">{{ $t('backups.configureBackupStorage.region') }}</label>
      <TextInput id="s3v4CompatRegionInput" v-model="providerConfig.region" />
      <small class="helper-text">{{ $t('backups.configureBackupStorage.regionHelperText') }}</small>
    </FormGroup>

    <FormGroup v-if="s3like(provider)">
      <label for="accessKeyIdInput">{{ $t('backups.configureBackupStorage.s3AccessKeyId') }}</label>
      <TextInput id="accessKeyIdInput" v-model="providerConfig.accessKeyId" required />
    </FormGroup>

    <FormGroup v-if="s3like(provider)">
      <label for="secretAccessKeyInput">{{ $t('backups.configureBackupStorage.s3SecretAccessKey') }}</label>
      <TextInput id="secretAccessKeyInput" v-model="providerConfig.secretAccessKey" required />
    </FormGroup>

    <FormGroup v-if="provider === 'gcs'">
      <input type="file" id="gcsKeyFileInput" style="display:none" accept="application/json, text/json" @change="onGcsKeyChange"/>
      <label for="gcsKeyInput">{{ $t('backups.configureBackupStorage.gcsServiceKey') }}{{ providerConfig.projectId ? ` - project: ${providerConfig.projectId}` : '' }}</label>
      <InputGroup>
        <input style="display: none" :value="providerConfig.credentials.client_email" required /> <!-- for form validation -->
        <TextInput readonly style="cursor: pointer; flex-grow: 1" v-model="providerConfig.credentials.client_email" placeholder="Service account key" onclick="document.getElementById('gcsKeyFileInput').click();"/>
        <Button tool icon="fa fa-upload" onclick="document.getElementById('gcsKeyFileInput').click();"/>
      </InputGroup>
      <div class="error-label" v-show="gcsFileParseError">{{ gcsFileParseError }}</div>
    </FormGroup>

    <FormGroup>
      <label for="formatInput">{{ $t('backups.configureBackupStorage.format') }} <sup><a href="https://docs.cloudron.io/backups/#backup-formats" class="help" target="_blank" tabindex="-1"><i class="fa fa-question-circle"></i></a></sup></label>
      <SingleSelect id="formatInput" v-model="format" :options="BACKUP_FORMATS" option-label="name" option-key="value" required />
      <div class="warning-label" v-show="format === 'rsync' && (s3like(provider) || provider === 'gcs') && !importOnly">{{ $t('backups.configureBackupStorage.s3LikeNote') }} <sup><a href="https://docs.cloudron.io/backups/#amazon-s3" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></div>
    </FormGroup>

    <!-- Filesystem/SSHFS/CIFS/NFS/EXT4/mountpoint -->
    <Checkbox v-if="(provider === 'filesystem' || mountlike(provider)) && !importOnly && format === 'rsync'" v-model="providerConfig.useHardlinks" :label="$t('backups.configureBackupStorage.hardlinksLabel')"/>

    <!-- CIFS/mountpoint -->
    <Checkbox v-if="(provider === 'mountpoint' || provider === 'cifs') && !importOnly && format === 'rsync'" v-model="providerConfig.preserveAttributes" :label="$t('backups.configureBackupStorage.preserveAttributesLabel')"/>

    <!-- mountpoint -->
    <Checkbox v-if="provider === 'mountpoint' && !importOnly && format === 'rsync'" v-model="providerConfig.chown" :label="$t('backups.configureBackupStorage.chown')"/>
  </div>
</template>
