#!/bin/bash

source /opt/scripts_local/shared_functions.sh

HOSTNAME=$(hostname)
export RCLONE_CONFIG=/opt/rclone/rclone.conf
# Create & config folders
sudo mkdir -p /opt/rclone \
/mnt/rclone_mount/rclone_{vmx-nas,vmx-load} \
/mnt/unionfs \
/rclone_cache \
/var/log/rclone
sudo chown root:sysadmin /opt/rclone \
/mnt/rclone_mount/rclone_{vmx-nas,vmx-load} \
/mnt/unionfs \
/rclone_cache \
/var/log/rclone
sudo chmod 770 /opt/rclone \
/mnt/rclone_mount/rclone_{vmx-nas,vmx-load} \
/mnt/unionfs \
/rclone_cache \
/var/log/rclone
# Copy config from vmx-nas
if [ "$HOSTNAME" == "vmx-nas" ]; then
  sudo rsync -avP /mnt/unionfs/shared/opt/rclone/rclone.conf /opt/rclone/
  sudo rsync -avP /mnt/unionfs/shared/etc/systemd/env_variables /etc/systemd/
  sudo rsync -avP /mnt/unionfs/shared/etc/systemd/system/ /etc/systemd/system/
  sudo rsync -avP /mnt/unionfs/scripts/rclone/rclone_rcd_svc.sh /opt/scripts_local
else
  sudo rsync -avP -e "ssh -o StrictHostKeyChecking=no" root@vmx-nas.swallow-grue.ts.net:/mnt/unionfs/shared/opt/rclone/rclone.conf /opt/rclone/
  sudo rsync -avP -e "ssh -o StrictHostKeyChecking=no" root@vmx-nas.swallow-grue.ts.net:/mnt/unionfs/shared/etc/systemd/env_variables /etc/systemd/
  sudo rsync -avP -e "ssh -o StrictHostKeyChecking=no" root@vmx-nas.swallow-grue.ts.net:/mnt/unionfs/shared/etc/systemd/system/ /etc/systemd/system/
  sudo rsync -avP -e "ssh -o StrictHostKeyChecking=no" root@vmx-nas.swallow-grue.ts.net:/mnt/unionfs/scripts/rclone/rclone_rcd_svc.sh /opt/scripts_local
fi
# Mergerfs Installation
source /opt/scripts_local/install_package.sh install_mergerfs.sh

# Rclone Installation
rclone version
if ! [ $? -eq 0 ]
then
  curl https://rclone.org/install.sh | sudo bash
fi
# Rclone Update
rclone selupdate >/dev/null 2>&1
# Fuse installation
sudo apt install fuse3
sudo sed -r -i.orig 's/#user_allow_other/user_allow_other/g' /etc/fuse.conf
# Fine-tuning
sudo chown root:sysadmin -R /opt/rclone/
sudo chmod 770 -R /opt/rclone/
sudo touch /var/log/rclone/rclone_{vmx-nas,dbc_media,vmx-down,o365,onedrive}.log
sudo chown root:sysadmin -R /var/log/rclone/
sudo chmod 770 -R /var/log/rclone/

sudo systemctl daemon-reload
sudo systemctl enable rclone_rcd rclone_vmx-nas rclone_vmx-load unionfs 
sudo systemctl start rclone_rcd rclone_vmx-nas rclone_vmx-load unionfs