#!/usr/bin/env bash
# MMI Traceability — map smb:// (or //server/share) to a Linux path
# Usage:
#   chmod +x linux-map-share.sh
#   ./linux-map-share.sh
#   ./linux-map-share.sh smb://server/MMI
# Or double-click in the file manager (Run in Terminal).
#
# Result path (paste in MMI → Settings → Shared folder):
#   /mnt/mmi-share

set -euo pipefail

APP_NAME="MMI Traceability"
INSTALL_DIR="${HOME}/Program-Traceability"
MOUNT_POINT="${MMI_SHARE_MOUNT:-/mnt/mmi-share}"
CRED_FILE="/etc/mmi-cifs.cred"
FSTAB_MARK="# MMI Traceability CIFS share"
RECORDS_JSON="${INSTALL_DIR}/Configuration/records_path.json"

log()  { echo -e "\n==> $*"; }
ok()   { echo "    OK: $*"; }
warn() { echo "    WARN: $*"; }
die()  { echo "ERROR: $*" >&2; exit 1; }

need_cmd() {
  command -v "$1" >/dev/null 2>&1 || die "Missing command: $1"
}

ask_yes() {
  local prompt="$1"
  local reply
  read -r -p "${prompt} [Y/n] " reply || true
  case "${reply:-Y}" in
    Y|y|yes|YES|"") return 0 ;;
    *) return 1 ;;
  esac
}

# Convert smb://  scb://  \\server\share  //server/share  →  host, share, extra path
parse_smb_url() {
  local raw="$1"
  raw="${raw#"${raw%%[![:space:]]*}"}"
  raw="${raw%"${raw##*[![:space:]]}"}"
  [[ -n "${raw}" ]] || die "Share URL is empty"

  raw="${raw//\\//}"
  raw="${raw#scb://}"
  raw="${raw#SCB://}"
  raw="${raw#smb://}"
  raw="${raw#SMB://}"
  raw="${raw#file://}"
  while [[ "${raw}" == //* ]]; do
    raw="${raw#/}"
  done
  raw="${raw#/}"
  raw="${raw%/}"

  # user@host/share  or  DOMAIN;user@host/share
  if [[ "${raw}" == *@* ]]; then
    local userpart="${raw%%@*}"
    raw="${raw#*@}"
    if [[ -z "${SMB_USER:-}" ]]; then
      if [[ "${userpart}" == *\;* ]]; then
        SMB_DOMAIN="${SMB_DOMAIN:-${userpart%%;*}}"
        SMB_USER="${userpart#*;}"
      else
        SMB_USER="${userpart%%:*}"
      fi
    fi
  fi

  SMB_HOST="${raw%%/*}"
  local rest=""
  if [[ "${raw}" == */* ]]; then
    rest="${raw#*/}"
  fi
  SMB_SHARE="${rest%%/*}"
  SMB_SUBPATH=""
  if [[ "${rest}" == */* ]]; then
    SMB_SUBPATH="${rest#*/}"
  fi

  [[ -n "${SMB_HOST}" ]] || die "Could not read server from URL"
  [[ -n "${SMB_SHARE}" ]] || die "Could not read share name from URL (example: smb://server/MMI)"

  UNC="//${SMB_HOST}/${SMB_SHARE}"
  if [[ -n "${SMB_SUBPATH}" ]]; then
    APP_PATH="${MOUNT_POINT}/${SMB_SUBPATH}"
  else
    APP_PATH="${MOUNT_POINT}"
  fi
}

write_records_path_json() {
  local path="$1"
  mkdir -p "$(dirname "${RECORDS_JSON}")"
  cat > "${RECORDS_JSON}" <<EOF
{
  "shared_path": "${path}",
  "mode": "shared_folder"
}
EOF
  ok "Wrote ${RECORDS_JSON}"
}

echo "========================================"
echo "  ${APP_NAME} — map shared folder"
echo "========================================"
echo "Mount point: ${MOUNT_POINT}"
echo "App path:    used in Settings → Shared folder"
echo

SMB_INPUT="${1:-${MMI_SMB_URL:-}}"
if [[ -z "${SMB_INPUT}" ]]; then
  echo "Examples:"
  echo "  smb://192.168.1.10/MMI"
  echo "  smb://fileserver/MMI"
  echo "  //fileserver/MMI"
  echo
  read -r -p "Share URL (smb://...): " SMB_INPUT
fi

parse_smb_url "${SMB_INPUT}"

echo
echo "Server:  ${SMB_HOST}"
echo "Share:   ${SMB_SHARE}"
echo "UNC:     ${UNC}"
[[ -n "${SMB_SUBPATH}" ]] && echo "Subpath: ${SMB_SUBPATH}"
echo "Linux:   ${APP_PATH}"
echo

if ! ask_yes "Mount this share at ${MOUNT_POINT}?"; then
  echo
  echo "Linux path for MMI Settings → Shared folder:"
  echo "  ${APP_PATH}"
  exit 0
fi

need_cmd sudo
need_cmd apt-get

log "Installing cifs-utils (needs sudo password once)"
sudo apt-get update -qq
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y cifs-utils
ok "cifs-utils ready"

SMB_USER="${SMB_USER:-${MMI_SMB_USER:-}}"
SMB_PASSWORD="${MMI_SMB_PASSWORD:-}"
SMB_DOMAIN="${SMB_DOMAIN:-${MMI_SMB_DOMAIN:-}}"

if [[ -z "${SMB_USER}" ]]; then
  read -r -p "Share username: " SMB_USER
fi
[[ -n "${SMB_USER}" ]] || die "Username is required"
if [[ -z "${SMB_PASSWORD}" ]]; then
  read -r -s -p "Share password: " SMB_PASSWORD
  echo
fi
if [[ -z "${SMB_DOMAIN}" ]]; then
  read -r -p "Share domain (Enter to skip): " SMB_DOMAIN
fi

log "Saving credentials to ${CRED_FILE}"
{
  echo "username=${SMB_USER}"
  echo "password=${SMB_PASSWORD}"
  if [[ -n "${SMB_DOMAIN}" ]]; then
    echo "domain=${SMB_DOMAIN}"
  fi
} | sudo tee "${CRED_FILE}" >/dev/null
sudo chmod 600 "${CRED_FILE}"
ok "Credentials saved (mode 600)"

MOUNT_OPTS="credentials=${CRED_FILE},uid=$(id -u),gid=$(id -g),file_mode=0775,dir_mode=0775,iocharset=utf8,nofail,_netdev"

log "Creating mount point ${MOUNT_POINT}"
sudo mkdir -p "${MOUNT_POINT}"

if mountpoint -q "${MOUNT_POINT}" 2>/dev/null; then
  log "Already mounted — unmounting to remount with new settings"
  sudo umount "${MOUNT_POINT}" || die "Could not unmount ${MOUNT_POINT}"
fi

log "Mounting ${UNC}"
if ! sudo mount -t cifs "${UNC}" "${MOUNT_POINT}" -o "${MOUNT_OPTS},vers=3.0"; then
  warn "SMB 3.0 failed — trying SMB 2.0"
  sudo mount -t cifs "${UNC}" "${MOUNT_POINT}" -o "${MOUNT_OPTS},vers=2.0" \
    || die "Mount failed. Check URL, username, password, and that the PC can reach ${SMB_HOST}."
fi
ok "Mounted ${UNC} → ${MOUNT_POINT}"

if [[ ! -d "${APP_PATH}" ]]; then
  warn "Subpath does not exist yet on the share: ${APP_PATH}"
  echo "    The share itself is mounted. Create the folder on the server, or use ${MOUNT_POINT}."
fi

FSTAB_LINE="${UNC} ${MOUNT_POINT} cifs ${MOUNT_OPTS},vers=3.0 0 0"
log "Saving mount in /etc/fstab (auto-mount after reboot)"
sudo cp /etc/fstab "/etc/fstab.mmi.bak.$(date +%Y%m%d%H%M%S)"
sudo awk -v mark="${FSTAB_MARK}" -v mp="${MOUNT_POINT}" '
  $0 == mark { skip=1; next }
  skip && $2 == mp { skip=0; next }
  skip { skip=0 }
  $2 == mp { next }
  { print }
' /etc/fstab | sudo tee /etc/fstab.tmp.mmi >/dev/null
{
  echo "${FSTAB_MARK}"
  echo "${FSTAB_LINE}"
} | sudo tee -a /etc/fstab.tmp.mmi >/dev/null
sudo mv /etc/fstab.tmp.mmi /etc/fstab
ok "fstab updated (backup in /etc/fstab.mmi.bak.*)"

if [[ -d "${INSTALL_DIR}" ]]; then
  log "Pointing MMI at the mapped path"
  write_records_path_json "${APP_PATH}"
else
  warn "MMI is not in ${INSTALL_DIR} yet — skip records_path.json"
  echo "    After linux-first-setup.sh, paste this path in Settings → Shared folder:"
  echo "    ${APP_PATH}"
fi

echo
echo "========================================"
echo "  Share mapped"
echo "========================================"
echo "UNC:         ${UNC}"
echo "Linux path:  ${APP_PATH}"
echo
echo "Use this path in MMI → Settings → Shared folder:"
echo "  ${APP_PATH}"
echo
echo "The app will copy Configuration from the share when it starts."
echo
if [[ -x "${INSTALL_DIR}/mmi" ]] && ask_yes "Launch ${APP_NAME} now?"; then
  nohup "${INSTALL_DIR}/mmi" >/dev/null 2>&1 &
  ok "Started ${APP_NAME}"
fi
