#!/bin/bash

#
# Copyright (C) 2022 Nethesis S.r.l.
# http://www.nethesis.it - nethserver@nethesis.it
#
# This script is part of NethServer.
#
# NethServer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# NethServer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NethServer.  If not, see COPYING.
#

set -e

source /etc/nethserver/agent.env
source "${AGENT_STATE_DIR}"/agent.env
source "${AGENT_STATE_DIR}"/environment
cd "${AGENT_STATE_DIR}/nethserver-nextcloud"
source bind.env

# Ensure endpoint is defined
: "${RSYNC_ENDPOINT:?}"
export RSYNC_PASSWORD

if [[ "${MIGRATE_ACTION}" == "finish" ]]; then
    # During the last, "finish" rsync run there must be no changes to
    # the database: stop the service early.
    systemctl stop httpd
fi

# Sync files: --owner --group --chown=82:82 are needed to map data for the www-data user
rsync -tr --owner --group --chown=82:82 -s --delete --exclude=appdata\* --exclude=nextcloud.log /var/lib/nethserver/nextcloud/ "${RSYNC_ENDPOINT}"/data/volumes/nextcloud-app-data/data/

# Create database dump
mysqldump -S /run/rh-mariadb105-mariadb/nextcloud-mysql.sock nextcloud > /var/lib/nethserver/nextcloud/dump.sql
rsync -tr /var/lib/nethserver/nextcloud/dump.sql "${RSYNC_ENDPOINT}"/data/state/restore/
rm -f /var/lib/nethserver/nextcloud/dump.sql

# Copy original config
rsync -tr /usr/share/nextcloud/config/config.php "${RSYNC_ENDPOINT}"/data/state/

if [[ "${MIGRATE_ACTION}" != "finish" ]]; then
    exit 0
fi

# Assert required vars are set
: "${IMPORT_TASK_ID:?}" "${NEXTCLOUD_VHOST:?}"

# Stop and disable Nextcloud
host=$(/sbin/e-smith/config getprop nextcloud VirtualHost)
# Setup migration page
mkdir -p ./webroot
cat - >webroot/index.html <<EOF
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Nextcloud Migration</title>
  </head>
  <body>
    <h1>Nextcloud Migration</h1>
    <p>Site has moved to &#9758; <a href="https://${host}">${host}</a></p>
  </body>
</html>
EOF

mkdir -p /etc/e-smith/templates-custom/etc/httpd/conf.d/{zz_nextcloud.conf,default-virtualhost.inc}
echo '# ns8migration' > /etc/e-smith/templates-custom/etc/httpd/conf.d/default-virtualhost.inc/40nextcloud
if [ -z "${host}" ]; then
   cat - >/etc/e-smith/templates-custom/etc/httpd/conf.d/zz_nextcloud.conf/10base <<EOF
# ns8migration
Alias /nextcloud /var/lib/nethserver/nethserver-ns8-migration/nethserver-nextcloud/webroot/
<Directory "/var/lib/nethserver/nethserver-ns8-migration/nethserver-nextcloud/webroot/">
  AllowOverride all
  Require all granted
</Directory>
EOF
else
    cat - >/etc/e-smith/templates-custom/etc/httpd/conf.d/zz_nextcloud.conf/10base <<EOF
# ns8migration
<VirtualHost *:80>
    IncludeOptional conf.d/default-virtualhost.inc
</VirtualHost>

<VirtualHost *:80>
   ServerName {{\$nextcloud{'VirtualHost'} || 'nextcloud.'.\$DomainName}}
   RedirectMatch 301 ^(?!/\.well-known/acme-challenge/).* https://{{\$nextcloud{'VirtualHost'} || 'nextcloud.'.\$DomainName}}
</VirtualHost>

<VirtualHost *:443>
  ServerName {{\$nextcloud{'VirtualHost'} || 'nextcloud.'.\$DomainName}}

  Alias / /var/lib/nethserver/nethserver-ns8-migration/nethserver-nextcloud/webroot/
  <Directory "/var/lib/nethserver/nethserver-ns8-migration/nethserver-nextcloud/webroot/">
     AllowOverride all
     Require all granted
  </Directory>

</VirtualHost>
EOF
/sbin/e-smith/expand-template /etc/httpd/conf.d/default-virtualhost.inc
/sbin/e-smith/expand-template /etc/httpd/conf.d/nextcloud.conf
/sbin/e-smith/expand-template /etc/httpd/conf.d/zz_nextcloud.conf
fi

# Terminate the rsync server
rsync "${RSYNC_ENDPOINT}"/terminate || :

# Wait until the import-module task has completed
ns8-action --attach wait "${IMPORT_TASK_ID}"

# Search for Samba or LDAP domain
domain=$(/sbin/e-smith/config getprop sssd Realm | tr '[:upper:]' '[:lower:]')
if [ -z "$domain" ]; then
   domain=${USER_DOMAIN:?}
fi

if [ -z "${host}" ]; then
    host=${NEXTCLOUD_VHOST}
fi
ns8-action --attach "module/${MODULE_INSTANCE_ID}" configure-module '{"host": "'$host'", "lets_encrypt": false, "http2https": true, "domain": "'$domain'"}'

systemctl start httpd
