#!/usr/bin/env bash
# ==============================================================================
# Ring2All Horizontal Cluster Automation — Universal Storage Mount Library
# Supports: GlusterFS Replica 3, NFSv4.1/NAS, Cloudflare R2, AWS S3,
#           Google Cloud Storage, Google Drive, Azure Blob, S3-Compatible
#           (MinIO/Wasabi/Backblaze B2/Spaces), and SFTP Storage Box.
#
# Strictly scoped to Horizontal Cluster deployments orchestrated by Ring2All NMS.
# Does NOT modify or affect Ring2All Standalone installations.
# ==============================================================================

# Generates /etc/softswitch/rclone-cluster.conf (chmod 600) and any auxiliary key file
# for cloud/external object or drive storage modes.
r2a_configure_rclone_storage() {
  local mode="$1"
  mkdir -p /etc/softswitch /var/cache/softswitch-storage
  chmod 755 /etc/softswitch
  local conf="/etc/softswitch/rclone-cluster.conf"

  case "$mode" in
    cloudflare_r2)
      : "${STORAGE_ACCESS_KEY:?STORAGE_ACCESS_KEY is required for Cloudflare R2}"
      : "${STORAGE_SECRET_KEY:?STORAGE_SECRET_KEY is required for Cloudflare R2}"
      : "${STORAGE_ENDPOINT:?STORAGE_ENDPOINT is required for Cloudflare R2}"
      cat << EOF > "$conf"
[r2a_storage]
type = s3
provider = Cloudflare
access_key_id = ${STORAGE_ACCESS_KEY}
secret_access_key = ${STORAGE_SECRET_KEY}
region = ${STORAGE_REGION:-auto}
endpoint = ${STORAGE_ENDPOINT}
acl = private
no_check_bucket = true
EOF
      ;;

    aws_s3)
      : "${STORAGE_ACCESS_KEY:?STORAGE_ACCESS_KEY is required for Amazon S3}"
      : "${STORAGE_SECRET_KEY:?STORAGE_SECRET_KEY is required for Amazon S3}"
      cat << EOF > "$conf"
[r2a_storage]
type = s3
provider = AWS
access_key_id = ${STORAGE_ACCESS_KEY}
secret_access_key = ${STORAGE_SECRET_KEY}
region = ${STORAGE_REGION:-us-east-1}
acl = private
${STORAGE_ENDPOINT:+endpoint = ${STORAGE_ENDPOINT}}
EOF
      ;;

    google_cloud_storage)
      if [[ -n "${STORAGE_SERVICE_ACCOUNT_B64:-}" ]]; then
        printf '%s' "$STORAGE_SERVICE_ACCOUNT_B64" | base64 -d > /etc/softswitch/gcs-sa.json
        chmod 600 /etc/softswitch/gcs-sa.json
        cat << EOF > "$conf"
[r2a_storage]
type = google cloud storage
service_account_file = /etc/softswitch/gcs-sa.json
location = ${STORAGE_REGION:-us-central1}
bucket_policy_only = true
EOF
      else
        : "${STORAGE_ACCESS_KEY:?STORAGE_ACCESS_KEY or Service Account JSON is required for Google Cloud Storage}"
        : "${STORAGE_SECRET_KEY:?STORAGE_SECRET_KEY is required for Google Cloud Storage HMAC}"
        cat << EOF > "$conf"
[r2a_storage]
type = s3
provider = Other
access_key_id = ${STORAGE_ACCESS_KEY}
secret_access_key = ${STORAGE_SECRET_KEY}
region = ${STORAGE_REGION:-us-central1}
endpoint = ${STORAGE_ENDPOINT:-https://storage.googleapis.com}
force_path_style = true
EOF
      fi
      ;;

    s3_compatible)
      : "${STORAGE_ACCESS_KEY:?STORAGE_ACCESS_KEY is required for S3-Compatible storage}"
      : "${STORAGE_SECRET_KEY:?STORAGE_SECRET_KEY is required for S3-Compatible storage}"
      : "${STORAGE_ENDPOINT:?STORAGE_ENDPOINT is required for S3-Compatible storage}"
      cat << EOF > "$conf"
[r2a_storage]
type = s3
provider = Other
access_key_id = ${STORAGE_ACCESS_KEY}
secret_access_key = ${STORAGE_SECRET_KEY}
region = ${STORAGE_REGION:-us-east-1}
endpoint = ${STORAGE_ENDPOINT}
force_path_style = ${STORAGE_FORCE_PATH_STYLE:-true}
acl = private
no_check_bucket = true
EOF
      ;;

    azure_blob)
      : "${STORAGE_AZURE_ACCOUNT:?STORAGE_AZURE_ACCOUNT is required for Azure Blob Storage}"
      if [[ -n "${STORAGE_SAS_TOKEN:-}" && "${STORAGE_SAS_TOKEN}" == http* ]]; then
        cat << EOF > "$conf"
[r2a_storage]
type = azureblob
account = ${STORAGE_AZURE_ACCOUNT}
sas_url = ${STORAGE_SAS_TOKEN}
EOF
      else
        : "${STORAGE_SECRET_KEY:?STORAGE_SECRET_KEY (Account Key) or SAS URL is required for Azure Blob}"
        cat << EOF > "$conf"
[r2a_storage]
type = azureblob
account = ${STORAGE_AZURE_ACCOUNT}
key = ${STORAGE_SECRET_KEY}
EOF
      fi
      ;;

    google_drive)
      cat << EOF > "$conf"
[r2a_storage]
type = drive
scope = drive
${STORAGE_GDRIVE_TEAM_DRIVE_ID:+team_drive = ${STORAGE_GDRIVE_TEAM_DRIVE_ID}}
${STORAGE_GDRIVE_FOLDER_ID:+root_folder_id = ${STORAGE_GDRIVE_FOLDER_ID}}
EOF
      if [[ -n "${STORAGE_SERVICE_ACCOUNT_B64:-}" ]]; then
        printf '%s' "$STORAGE_SERVICE_ACCOUNT_B64" | base64 -d > /etc/softswitch/gdrive-sa.json
        chmod 600 /etc/softswitch/gdrive-sa.json
        echo "service_account_file = /etc/softswitch/gdrive-sa.json" >> "$conf"
      elif [[ -n "${STORAGE_OAUTH_TOKEN_B64:-}" ]]; then
        local token_json
        token_json="$(printf '%s' "$STORAGE_OAUTH_TOKEN_B64" | base64 -d)"
        echo "token = ${token_json}" >> "$conf"
      else
        r2a_fail "Google Drive requires either a Service Account JSON or an OAuth2 Token JSON."
      fi
      ;;

    sftp_external)
      : "${STORAGE_SFTP_HOST:?STORAGE_SFTP_HOST is required for SFTP Storage}"
      : "${STORAGE_SFTP_USER:?STORAGE_SFTP_USER is required for SFTP Storage}"
      : "${STORAGE_SFTP_PASSWORD:?STORAGE_SFTP_PASSWORD is required for SFTP Storage}"
      local obscured_pass
      obscured_pass="$(rclone obscure "$STORAGE_SFTP_PASSWORD")"
      cat << EOF > "$conf"
[r2a_storage]
type = sftp
host = ${STORAGE_SFTP_HOST}
port = ${STORAGE_SFTP_PORT:-22}
user = ${STORAGE_SFTP_USER}
pass = ${obscured_pass}
EOF
      ;;

    *)
      r2a_fail "Unsupported cloud/external storage driver: ${mode}"
      ;;
  esac

  chmod 600 "$conf"
  chown root:root "$conf"

  # Ensure user_allow_other is enabled in /etc/fuse.conf so GID 2000 services can access mounts
  if [[ -f /etc/fuse.conf ]]; then
    sed -i 's/^#user_allow_other/user_allow_other/' /etc/fuse.conf || true
    grep -q '^user_allow_other' /etc/fuse.conf || echo 'user_allow_other' >> /etc/fuse.conf
  else
    echo 'user_allow_other' > /etc/fuse.conf
  fi
}

# Installs and starts a systemd VFS write-back mount service for one logical volume
# (ss-recordings, ss-uploads, or ss-music). Uses local SSD cache (`--vfs-cache-mode full`)
# so active real-time Telephony recordings write locally with zero audio jitter and upload
# cleanly after hangup.
r2a_mount_rclone_volume() {
  local mode="$1"
  local vol_name="$2"      # e.g. ss-recordings | ss-uploads | ss-music
  local mount_point="$3"   # e.g. /var/lib/softswitch/recordings
  local prefix="${STORAGE_BASE_PREFIX:-ring2all}"
  prefix="${prefix#/}"
  prefix="${prefix%/}"

  local remote_target=""
  if [[ "$mode" == "google_drive" ]]; then
    remote_target="r2a_storage:${prefix:+${prefix}/}${vol_name}"
  elif [[ "$mode" == "sftp_external" ]]; then
    local sftp_root="${STORAGE_SFTP_PATH:-/ring2all}"
    sftp_root="${sftp_root%/}"
    remote_target="r2a_storage:${sftp_root}/${vol_name}"
  else
    : "${STORAGE_BUCKET:?STORAGE_BUCKET is required for ${mode}}"
    remote_target="r2a_storage:${STORAGE_BUCKET}/${prefix:+${prefix}/}${vol_name}"
  fi

  local cache_gb="${STORAGE_VFS_CACHE_MAX_SIZE_GB:-10}"
  local cache_hours="${STORAGE_VFS_CACHE_MAX_AGE_HOURS:-24}"
  local cache_dir="/var/cache/softswitch-storage/${vol_name}"
  local svc_name="r2a-storage-${vol_name}.service"

  mkdir -p "$mount_point" "$cache_dir"
  chgrp "${MEDIA_GID:-2000}" "$cache_dir" 2>/dev/null || true
  chmod 2775 "$cache_dir" 2>/dev/null || true

  # Ensure remote logical folder exists before mounting
  rclone --config /etc/softswitch/rclone-cluster.conf mkdir "$remote_target" 2>/dev/null || true

  # Unmount any stale previous mount on this path before starting the new service
  if mountpoint -q "$mount_point"; then
    fusermount3 -uz "$mount_point" 2>/dev/null || umount -l "$mount_point" 2>/dev/null || true
  fi

  cat << EOF > "/etc/systemd/system/${svc_name}"
[Unit]
Description=Ring2All Horizontal Cluster Storage Mount (${mode} -> ${vol_name})
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
ExecStartPre=/usr/bin/mkdir -p ${mount_point} ${cache_dir}
ExecStart=/usr/bin/rclone mount ${remote_target} ${mount_point} \\
  --config /etc/softswitch/rclone-cluster.conf \\
  --allow-other \\
  --gid ${MEDIA_GID:-2000} \\
  --umask 002 \\
  --vfs-cache-mode full \\
  --vfs-write-back 5s \\
  --vfs-cache-max-age ${cache_hours}h \\
  --vfs-cache-max-size ${cache_gb}G \\
  --dir-cache-time 30s \\
  --vfs-read-chunk-size 16M \\
  --buffer-size 32M \\
  --cache-dir ${cache_dir} \\
  --log-level NOTICE
ExecStop=/bin/fusermount3 -uz ${mount_point}
Restart=always
RestartSec=5
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

  systemctl daemon-reload
  systemctl enable --now "$svc_name"

  local waited=0
  while ! mountpoint -q "$mount_point" && (( waited < 20 )); do
    sleep 1
    waited=$((waited + 1))
  done
  mountpoint -q "$mount_point" || r2a_fail "Storage mount failed for ${vol_name} (${mode}) at ${mount_point}."
}

# Mounts a set of logical volumes passed as "vol_name:mount_point" pairs according to STORAGE_MODE.
# Example: r2a_mount_cluster_storage "ss-recordings:/var/lib/softswitch/recordings" "ss-music:/usr/share/softswitch/sounds/music"
r2a_mount_cluster_storage() {
  local mode="${STORAGE_MODE:-glusterfs_replica3}"
  r2a_ensure_media_group

  mkdir -p /etc/softswitch
  cat << EOF > /etc/softswitch/storage.env
STORAGE_MODE=${mode}
STORAGE_BUCKET=${STORAGE_BUCKET:-}
STORAGE_ENDPOINT=${STORAGE_ENDPOINT:-}
STORAGE_NFS_SERVER=${STORAGE_NFS_SERVER:-}
EOF
  chmod 600 /etc/softswitch/storage.env

  case "$mode" in
    glusterfs_replica3)
      : "${FS_NODE_HOSTNAMES:?FS_NODE_HOSTNAMES is required when STORAGE_MODE=glusterfs_replica3}"
      IFS=',' read -ra FS_HOSTS <<< "$FS_NODE_HOSTNAMES"
      local fs_primary
      fs_primary="$(echo "${FS_HOSTS[0]}" | xargs)"
      local fs_backups=""
      for (( i=1; i<${#FS_HOSTS[@]}; i++ )); do
        local h
        h="$(echo "${FS_HOSTS[$i]}" | xargs)"
        fs_backups+="${h}:"
      done
      fs_backups="${fs_backups%:}"

      apt-get install -y glusterfs-client
      for spec in "$@"; do
        local vol="${spec%%:*}"
        local mnt="${spec#*:}"
        mkdir -p "$mnt"
        if ! mountpoint -q "$mnt"; then
          mount -t glusterfs -o "backup-volfile-servers=${fs_backups}" "${fs_primary}:/${vol}" "$mnt"
        fi
        if ! grep -q " ${mnt} " /etc/fstab; then
          echo "${fs_primary}:/${vol} ${mnt} glusterfs defaults,_netdev,backup-volfile-servers=${fs_backups} 0 0" >> /etc/fstab
        fi
      done
      ;;

    nfs_external)
      : "${STORAGE_NFS_SERVER:?STORAGE_NFS_SERVER is required when STORAGE_MODE=nfs_external}"
      : "${STORAGE_NFS_EXPORT_PATH:?STORAGE_NFS_EXPORT_PATH is required when STORAGE_MODE=nfs_external}"
      local nfs_root="${STORAGE_NFS_EXPORT_PATH%/}"
      local nfs_opts="${STORAGE_NFS_OPTIONS:-nfsvers=4.1,_netdev,hard,timeo=600,retrans=2}"

      apt-get install -y nfs-common
      # Ensure subdirectories exist inside the exported NFS root
      local tmp_nfs="/mnt/r2a-nfs-init"
      mkdir -p "$tmp_nfs"
      if mount -t nfs -o "$nfs_opts" "${STORAGE_NFS_SERVER}:${nfs_root}" "$tmp_nfs"; then
        for spec in "$@"; do
          local vol="${spec%%:*}"
          mkdir -p "${tmp_nfs}/${vol}"
          chgrp "${MEDIA_GID:-2000}" "${tmp_nfs}/${vol}" 2>/dev/null || true
          chmod 2775 "${tmp_nfs}/${vol}" 2>/dev/null || true
        done
        umount "$tmp_nfs" 2>/dev/null || true
      fi
      rmdir "$tmp_nfs" 2>/dev/null || true

      for spec in "$@"; do
        local vol="${spec%%:*}"
        local mnt="${spec#*:}"
        mkdir -p "$mnt"
        if ! mountpoint -q "$mnt"; then
          mount -t nfs -o "$nfs_opts" "${STORAGE_NFS_SERVER}:${nfs_root}/${vol}" "$mnt"
        fi
        if ! grep -q " ${mnt} " /etc/fstab; then
          echo "${STORAGE_NFS_SERVER}:${nfs_root}/${vol} ${mnt} nfs ${nfs_opts} 0 0" >> /etc/fstab
        fi
      done
      ;;

    cloudflare_r2|aws_s3|google_cloud_storage|s3_compatible|azure_blob|google_drive|sftp_external)
      apt-get install -y rclone fuse3
      r2a_configure_rclone_storage "$mode"
      for spec in "$@"; do
        local vol="${spec%%:*}"
        local mnt="${spec#*:}"
        r2a_mount_rclone_volume "$mode" "$vol" "$mnt"
      done
      ;;

    *)
      r2a_fail "Unknown STORAGE_MODE: ${mode}"
      ;;
  esac
}
