#!/bin/bash

# SU privileges (root)
if [ "$EUID" -ne 0 ]; then
  echo "Error: Please execute this script as root (sudo ./install.sh ...)"
  echo "If you dont want to install the Suite to all users just decompressed all tar.gz files in a single directory"
  exit 1
fi

# Directory variables according to Linux FHS
DEFAULT_BASE_DIR="/opt/contacter"
DEFAULT_VAR_DIR="/var/opt/contacter/models"
FORCE_INSTALL=false
CUSTOM_PATH=""
TARGET_FILE=""

# Diretoria final onde os modelos AI vão morar
EMBEDDING_DIR="$DEFAULT_VAR_DIR/deepghs/embedding"
SEGMENTATION_DIR="$DEFAULT_VAR_DIR/Alkd/segmentation"

# Absolute final paths for the model files
EMBEDDING_PATH="$EMBEDDING_DIR/embedding_model.onnx"
SEGMENTATION_PATH="$SEGMENTATION_DIR/segmentation_model.onnx"

# Absolute URLs for Hugging Face (Modelos and Credits)
URL_EMB_MODEL="https://huggingface.com/deepghs/pyannote-embedding-onnx/resolve/main/model.onnx"
URL_EMB_README="https://huggingface.co/deepghs/pyannote-embedding-onnx/resolve/main/README.md"

URL_SEG_MODEL="https://huggingface.com/Alkd/speech-turn-detector-onnx/resolve/main/model.onnx"
URL_SEG_README="https://huggingface.co/Alkd/speech-turn-detector-onnx/resolve/main/README.md"

if [ "$#" -lt 1 ]; then
  echo "Error: Missing parameters."
  exit 1
fi

TARGET_FILE="$1"
shift

# Dynamic options processing
while [ "$#" -gt 0 ]; do
  case "$1" in
    -force) FORCE_INSTALL=true; shift ;;
    -name) CUSTOM_PATH="$2"; shift 2 ;;
    -embedding) EMBEDDING_PATH="$2"; EMBEDDING_DIR=$(dirname "$2"); shift 2 ;;
    -segmentation) SEGMENTATION_PATH="$2"; SEGMENTATION_DIR=$(dirname "$2"); shift 2 ;;
    *) echo "Warning: Unknow option '$1' ignored."; shift ;;
  esac
done

BASE_FILE_NAME=$(basename "$TARGET_FILE" .tar.gz)

# =====================================================================
# FLUX A: LIBRARIES INSTALLATION (Files 'contacterlib')
# =====================================================================
if [[ "$BASE_FILE_NAME" == contacterlib* ]]; then
  echo "=== [Phase: Libraries Installation] ==="

  if [ -n "$CUSTOM_PATH" ]; then
    TARGET_LIB_DIR="$CUSTOM_PATH"
  else
    TARGET_LIB_DIR="$DEFAULT_BASE_DIR/$BASE_FILE_NAME"
  fi

  if [ "$FORCE_INSTALL" = true ]; then
    if [ ! -f "$TARGET_FILE" ]; then echo "ErroR: OpTION -force requeires the physicam file."; exit 1; fi
    echo "-> Forcing reinstallation in: $TARGET_LIB_DIR"
    rm -rf "$TARGET_LIB_DIR"
    mkdir -p "$TARGET_LIB_DIR"
    tar -xzf "$TARGET_FILE" -C "$TARGET_LIB_DIR"
  elif [ -d "$TARGET_LIB_DIR" ] && [ "$(ls -A "$TARGET_LIB_DIR")" ]; then
    echo "-> The libraris already exist in '$TARGET_LIB_DIR' Nothing will be done."
  else
    if [ ! -f "$TARGET_FILE" ]; then echo "ErroR: FiLE '$TARGET_FILE' necessary."; exit 1; fi
    echo "-> Extraction the libraries to: $TARGET_LIB_DIR"
    mkdir -p "$TARGET_LIB_DIR"
    tar -xzf "$TARGET_FILE" -C "$TARGET_LIB_DIR"
  fi

# =====================================================================
# FLUX B: BINARIES INSTALLATION OR UPGRADING AND PYANNOTE DOWNLOADS
# =====================================================================
else
  echo "=== [Phase: Binaries Installation] ==="
  
  if [ ! -f "$TARGET_FILE" ]; then
    echo "Error: Binary file '$TARGET_FILE' was not found."
    exit 1
  fi

  SUFIX_LIB=$(echo "$BASE_FILE_NAME" | sed 's/.*_//') 
  LIB_DIR_NAME="contacter$SUFIX_LIB"

  if [ -n "$CUSTOM_PATH" ]; then
    TARGET_BIN_DIR="$CUSTOM_PATH"
  else
    TARGET_BIN_DIR="$DEFAULT_BASE_DIR/$LIB_DIR_NAME"
  fi

  if [ ! -d "$TARGET_BIN_DIR" ]; then
    echo "Error: The dependency directory '$TARGET_BIN_DIR' does not exist. Install the libraries first."
    exit 1
  fi

  echo "-> Copying new binaries to: $TARGET_BIN_DIR"
  TMP_DIR=$(mktemp -d)
  tar -xzf "$TARGET_FILE" -C "$TMP_DIR"

  for BINARY_PATH in "$TMP_DIR"/*; do
    [ -e "$BINARY_PATH" ] || continue
    BINARY_NAME=$(basename "$BINARY_PATH")
    FINAL_TARGET="$TARGET_BIN_DIR/$BINARY_NAME"

    mv -f "$BINARY_PATH" "$FINAL_TARGET"
    chmod 755 "$FINAL_TARGET"
    ln -sf "$FINAL_TARGET" "/usr/local/bin/$BINARY_NAME"
    echo "   * Global link updated: /usr/local/bin/$BINARY_NAME"
  done
  rm -rf "$TMP_DIR"

  # --- DOWNLOAD OF THE AI MODELS AND CREDITS FILES ---
  echo ""
  echo "=== [ONNX AI Models verification (Pyannote)] ==="
  
  DOWNLOAD_CMD=""
  if command -v wget &> /dev/null; then DOWNLOAD_CMD="wget -q -O"; elif command -v curl &> /dev/null; then DOWNLOAD_CMD="curl -sL -o"; fi
  if [ -z "$DOWNLOAD_CMD" ]; then echo "Error: You need wget or curl installed to download the models."; exit 1; fi

 # 1. Processing Embeddings and its Credits
  mkdir -p "$EMBEDDING_DIR"
  EMB_MODEL_NAME=$(basename "$URL_EMB_MODEL")
  # Absolute final paths for the model files
  EMBEDDING_PATH="$EMBEDDING_DIR/$EMB_MODEL_NAME"

  if [ -f "$EMBEDDING_PATH" ]; then
    echo "-> [OK] Embedding Model already present."
  else
    echo "-> [Download] Downloading the Embedding Model Files..."
    $DOWNLOAD_CMD "$EMBEDDING_PATH" "$URL_EMB_MODEL"
    
    # Extract the Credits file name from the URL
    EMB_CREDIT_NAME=$(basename "$URL_EMB_README")
    $DOWNLOAD_CMD "$EMBEDDING_DIR/$EMB_CREDIT_NAME" "$URL_EMB_README"
  fi

  # 2. Processing Segmentation and its Credits
  mkdir -p "$SEGMENTATION_DIR"
  SEG_MODEL_NAME=$(basename "$URL_SEG_MODEL")
  # Absolute final paths for the model files
  SEGMENTATION_PATH="$SEGMENTATION_DIR/$SEG_MODEL_NAME"
  if [ -f "$SEGMENTATION_PATH" ]; then
    echo "-> [OK] Segmentation Model already present."
  else
    echo "-> [Download] Downloading the Segmentation Model Files..."
    $DOWNLOAD_CMD "$SEGMENTATION_PATH" "$URL_SEG_MODEL"
    
    # Extrai dinamicamente o nome do ficheiro a partir do URL (ex: README.md)
    SEG_CREDIT_NAME=$(basename "$URL_SEG_README")
    $DOWNLOAD_CMD "$SEGMENTATION_DIR/$SEG_CREDIT_NAME" "$URL_SEG_README"
  fi

  echo "-> [Credits] AI Models and Credits where stored"
fi

# =====================================================================
# GLOCAL SECURITY PERMISSION ADJUSTMEMTS
# =====================================================================
echo "-> Applying file security policies..."
if [ -d "$DEFAULT_BASE_DIR" ]; then
  chown -R root:root "$DEFAULT_BASE_DIR"
  find "$DEFAULT_BASE_DIR" -type d -exec chmod 755 {} \;
  find "$DEFAULT_BASE_DIR" -type f -exec chmod 755 {} \; # Files in /opt/contacter/contacterlibA.B/ maintain the load execution to the native libraries .so
fi

if [ -d "/var/opt/contacter" ]; then
  chown -R root:root "/var/opt/contacter"
  find "/var/opt/contacter" -type d -exec chmod 755 {} \;
  find "/var/opt/contacter" -type f -exec chmod 644 {} \; # .onnx Models and Credit files will maintain read only permissions
fi

echo "=== Concluded with sucess (We hope. If not let us know)! ==="