#!/bin/bash

# NUPST Installer Script
# Downloads and installs NUPST globally on the system
# Can be used directly with curl: curl -sSL https://code.foss.global/serve.zone/nupst/raw/branch/main/install.sh | sudo bash

# Check if running as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run as root (sudo bash install.sh or pipe to sudo bash)"
  exit 1
fi

# Detect if script is being piped or run directly
PIPED=0
if [ ! -t 0 ]; then
  # Being piped, need to clone the repo
  PIPED=1
fi

# Define installation directory
INSTALL_DIR="/opt/nupst"
REPO_URL="https://code.foss.global/serve.zone/nupst.git"

if [ $PIPED -eq 1 ]; then
  echo "Installing NUPST from remote repository..."
  
  # Check if git is installed
  if ! command -v git &> /dev/null; then
    echo "Git is required but not installed. Please install git first."
    exit 1
  fi
  
  # Check if installation directory exists
  if [ -d "$INSTALL_DIR" ] && [ -d "$INSTALL_DIR/.git" ]; then
    echo "Existing installation found at $INSTALL_DIR. Updating..."
    cd "$INSTALL_DIR"
    
    # Try to update the repository
    git fetch origin
    git reset --hard origin/main
    
    if [ $? -ne 0 ]; then
      echo "Failed to update repository. Reinstalling..."
      cd /
      rm -rf "$INSTALL_DIR"
      mkdir -p "$INSTALL_DIR"
      git clone --depth 1 $REPO_URL "$INSTALL_DIR"
    else
      echo "Repository updated successfully."
    fi
  else
    # Fresh installation
    if [ -d "$INSTALL_DIR" ]; then
      echo "Removing previous installation at $INSTALL_DIR..."
      rm -rf "$INSTALL_DIR"
    fi
    
    # Create installation directory
    mkdir -p "$INSTALL_DIR"
    
    # Clone the repository
    echo "Cloning NUPST repository to $INSTALL_DIR..."
    git clone --depth 1 $REPO_URL "$INSTALL_DIR"
  fi
  
  if [ $? -ne 0 ]; then
    echo "Failed to clone/update repository. Please check your internet connection."
    exit 1
  fi
  
  # Set script directory to the cloned repo
  SCRIPT_DIR="$INSTALL_DIR"
else
  # Running directly from within the repo
  SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
fi

# Run setup script
echo "Running setup script..."
bash "$SCRIPT_DIR/setup.sh"

# Install globally
echo "Installing NUPST globally..."
ln -sf "$SCRIPT_DIR/bin/nupst" /usr/local/bin/nupst

# Installation completed
if [ $PIPED -eq 1 ]; then
  echo "NUPST has been installed globally at $INSTALL_DIR"
else
  echo "NUPST has been installed globally."
fi

echo "You can now run 'nupst' from anywhere."
echo ""
echo "To get started, try:"
echo "  nupst help"
echo "  nupst setup  # To configure your UPS connection"