#!/usr/bin/env bash

# Exit codes
# 0 - Success
# 2 - Unsupported OS/architecture
# 3 - Login error
# 4 - Configuration issue
# 5 - Service timeout
# 6 - Invalid user_id format

set -euo pipefail

# Create temporary directory
tmp_dir=$(mktemp -d 2>/dev/null || mktemp -d -t 'ringlink-install.XXXXXXXXXX')
trap 'rm -rf "$tmp_dir"' EXIT
cd "$tmp_dir"

# Parse arguments
CONFIG_KEY=""
USER_ID=""
URL=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --config-key)
      CONFIG_KEY="$2"
      shift 2
      ;;
    --user-id)
      USER_ID="$2"
      shift 2
      ;;
    --url)
      URL="$2"
      shift 2
      ;;
    *)
      echo "Unknown argument: $1"
      exit 1
      ;;
  esac
done

# Check if user_id is an integer
if [[ -n "$USER_ID" && ! "$USER_ID" =~ ^[0-9]+$ ]]; then
  echo "Error: user_id must be an integer."
  exit 6
fi

# Detect OS
OS="$(uname)"
binTgtDir="/usr/local/bin"
case "$OS" in
  Linux)
    OS='unknown-linux-gnu'
    ;;
  Darwin)
    OS='apple-darwin'
    ;;
  *)
    echo "Error: Unsupported OS '$OS'."
    exit 2
    ;;
esac

# Detect architecture
ARCH="$(uname -m)"
case "$ARCH" in
  x86_64 | amd64)
    ARCH='x86_64'
    ;;
  aarch64 | arm64)
    ARCH='aarch64'
    ;;
  *)
    echo "Error: Unsupported architecture '$ARCH'."
    exit 2
    ;;
esac

# Download and extract
download_link="https://assets.aixrelay.com/ringlink-core-latest-${ARCH}-${OS}.tar.gz"
ringlink_tar_gz="ringlink-core-latest-${ARCH}-${OS}.tar.gz"

echo "Downloading: $download_link"
if ! curl -fSLO --progress-bar "$download_link"; then
  echo "Error: Failed to download from $download_link."
  exit 1
fi

echo "Extracting: $ringlink_tar_gz"
if ! tar xzf "$ringlink_tar_gz"; then
  echo "Error: Failed to extract $ringlink_tar_gz."
  exit 1
fi

# Install binaries
case "$OS" in
  'unknown-linux-gnu')
    sudo install -m 0755 ringlink-cli /usr/bin/ringlink-cli
    sudo install -m 0755 ringlink-daemon /usr/sbin/ringlink-daemon

    if ! sudo ringlink-cli install /usr/sbin/ringlink-daemon; then
      echo "Error: Failed to install ringlink daemon."
      exit 1
    fi

    sudo systemctl enable ringlink
    sudo systemctl restart ringlink
    ;;
  'apple-darwin')
    sudo mkdir -p "$binTgtDir"
    sudo install -m 0755 ringlink-cli "$binTgtDir/ringlink-cli"
    sudo install -m 0755 ringlink-daemon "$binTgtDir/ringlink-daemon"
    ;;
  *)
    echo "Error: Unsupported OS '$OS' during installation."
    exit 2
    ;;
esac

# Create configuration file if parameters are provided
if [[ -n "$CONFIG_KEY" && -n "$USER_ID" ]]; then
  CONFIG_DIR="/etc/ringlink"
  CONFIG_FILE="$CONFIG_DIR/config.toml"
  sudo mkdir -p "$CONFIG_DIR"
  
  # Clear the existing config.toml file
  echo "Clearing existing configuration file at $CONFIG_FILE"
  sudo truncate -s 0 "$CONFIG_FILE"

  echo "Creating configuration file at $CONFIG_FILE"
  sudo tee "$CONFIG_FILE" > /dev/null <<EOF
[server]
user_id = $USER_ID
token = "$CONFIG_KEY"
EOF

  # Add the URL if provided
  if [[ -n "$URL" ]]; then
    echo "url = \"$URL\"" | sudo tee -a "$CONFIG_FILE" > /dev/null
  fi

  echo "Configuration file created successfully."

  # Restart the ringlink service to apply new configuration
  echo "Restarting ringlink service to apply the new configuration..."
  sudo systemctl restart ringlink

  # Check the ringlink-cli status with retry mechanism (max 5 seconds)
  echo "Checking ringlink-cli status..."
  max_attempts=5
  attempt=1
  status=""

  while [[ $attempt -le $max_attempts ]]; do
    status=$(ringlink-cli status)
    if [[ "$status" =~ "Running" ]]; then
      echo "ringlink-cli is running and the configuration is correct."
      exit 0
    elif [[ "$status" =~ "NotLogin" ]]; then
      echo "Error: Login failed. Please check your credentials."
      echo "Check logs at /var/log/ring-link/ for more details."
      # Check logs for additional information
      if [ -d "/var/log/ring-link" ]; then
        echo "Latest log files from /var/log/ring-link/:"
        sudo ls -l /var/log/ring-link/
        sudo tail -n 10 /var/log/ring-link/*
      else
        echo "Log directory /var/log/ring-link does not exist or is empty."
      fi
      exit 3
    fi

    # If status is not "Running" or "NotLogin", wait and retry
    echo "Waiting for ringlink-cli to reach the 'Running' state... Attempt $attempt of $max_attempts"
    sleep 1
    ((attempt++))
  done

  # If the status is still not "Running" after 5 attempts
  echo "Error: ringlink-cli did not reach the 'Running' state within the timeout period."
  exit 5
fi

# Verify installation without config-key and user-id
if ! version=$(ringlink-cli --version 2>/dev/null | head -n 1); then
  echo "Error: Failed to verify the installation of ringlink-cli."
  exit 1
fi

# Success message
echo -e "\n$version has been successfully installed."
echo 'Run "ringlink-cli login" to complete setup.'
exit 0
