#!/bin/bash

[[ $EUID != 0 ]] && echo "sudo required!" && exit
[[ $(pidof -x "$(basename "$0")" -o %PPID) ]] && echo "Already running, exiting..." && exit 1
# Loop until tailscale service is up and connected
while ! systemctl is-active --quiet tailscaled.service && [[ $(tailscale status --peers=false --json=true | jq -r '.Self.Online') = "true" ]]
    do sleep 2
done
chmod +rx /mnt

UnMount() {
   MY_MNT=$1
   [[ $(mount |awk '{print $3}'| grep -w "$MY_MNT") != '' ]]  && fusermount -uz "$MY_MNT"
}

NfsMount() {
   SRV_NFS=$1
   MNT_NFS=$2
   ROOT_NFS=$3
   OPTION_NFS=rsize=4096,wsize=4096,rw,nfsvers=3
   MOUNTPOINT_NFS="/mnt/$SRV_NFS/$MNT_NFS"
   mkdir -p "$MOUNTPOINT_NFS"
   UnMount "$MOUNTPOINT_NFS"
   mount -t nfs -o "$OPTION_NFS" "$SRV_NFS.swallow-grue.ts.net:/$ROOT_NFS/$MNT_NFS" "$MOUNTPOINT_NFS"
}

BindFsMount() {
   SRV_BFS=$1
   MNT_BFS=$2
   USER_BFS=dbi
   GROUP_BFS=users
   PERM_BFS=0777
   if [ "$SRV_BFS" == "kut-nas" ]; then
      MOUNTPOINT_BFS="/mnt/$MNT_BFS"
      ROOT_BFS="/mnt/$SRV_BFS/$MNT_BFS"
   elif [ "$SRV_BFS" == "kom" ]; then
      MOUNTPOINT_BFS="/data/$SRV_BFS/$MNT_BFS"
      ROOT_BFS="/mnt/$SRV_BFS/$MNT_BFS"
      USER_BFS=backup
      GROUP_BFS=backup
      PERM_BFS=0775
   elif [ "$SRV_BFS" == "kyt" ]; then
      MOUNTPOINT_BFS="/data/$SRV_BFS"
      ROOT_BFS="/mnt/$SRV_BFS/media"
   elif [ "$SRV_BFS" == "kut-download" ]; then
      MOUNTPOINT_BFS="/data/$SRV_BFS"
      ROOT_BFS="/mnt/$SRV_BFS/move"
   elif [ "$SRV_BFS" == "vmx-nas" ]; then
      MOUNTPOINT_BFS="/data/$SRV_BFS"
      ROOT_BFS="/mnt/$SRV_BFS"
   fi
   mkdir -p "$MOUNTPOINT_BFS"
   UnMount "$MOUNTPOINT_BFS"
   bindfs --force-user="$USER_BFS" --force-group="$GROUP_BFS" --perms="$PERM_BFS" "$ROOT_BFS" "$MOUNTPOINT_BFS"
}
#-------------- kut-nas -------------------------
kut-nas-mount() {
   MY_MOUNTS=(backup ebooks inbox outbox public scripts)
   MY_SERVER=kut-nas
   for MY_MOUNT in "${MY_MOUNTS[@]}"
   do
      NfsMount "$MY_SERVER" "$MY_MOUNT" "export"
      BindFsMount "$MY_SERVER" "$MY_MOUNT"
   done
}
#-------------- kom -------------------------
kom-mount() {
   MY_MOUNTS=(media backup pbsbackup)
   MY_SERVER=kom
   for MY_MOUNT in "${MY_MOUNTS[@]}"
   do
      NfsMount "$MY_SERVER" "$MY_MOUNT" "data"
      BindFsMount "$MY_SERVER" "$MY_MOUNT"
   done
}
#-------------- vmx-nas -------------------------
vmx-nas-mount() {
   MY_MOUNTS=(series movies cache)
   MY_SERVER=vmx-nas
   for MY_MOUNT in "${MY_MOUNTS[@]}"
   do
      NfsMount "$MY_SERVER" "$MY_MOUNT" "export"
      BindFsMount "$MY_SERVER" "$MY_MOUNT"
   done
}
#-------------- kut-download -------------------------
kut-download-mount() {
   MY_MOUNT=(move)
   MY_SERVER=kut-download
   for MY_MOUNT in "${MY_MOUNTS[@]}"
   do
      NfsMount "$MY_SERVER" "$MY_MOUNT" "mnt"
      BindFsMount "$MY_SERVER" "$MY_MOUNT"
   done
}




if mountpoint /mnt/scripts > /dev/null 2>&1; then
   rsync /mnt/scripts/tailscale_delayed_mount.sh /opt/scripts_local/
fi
