#!/bin/bash
# portman — one-time install script for macOS, Linux, and Windows (via WSL)
# Engineered by Codermasky
# Run this once from your terminal: bash portman_install.sh

set -e

PORTMAN_DIR="$HOME/.portman"
PORTMAN_PY="$PORTMAN_DIR/portman.py"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo ""
echo "  Installing portman..."
echo ""

# 1. Create ~/.portman/ and copy the script from ~/Sandbox/portman/
mkdir -p "$PORTMAN_DIR"
cp "$(dirname "$0")/portman.py" "$PORTMAN_PY"
chmod +x "$PORTMAN_PY"
echo "  ✓  Copied portman.py → $PORTMAN_PY"

# 2. Detect shell and config file
SHELL_NAME=$(basename "$SHELL")
if [ "$SHELL_NAME" = "zsh" ]; then
  RCFILE="$HOME/.zshrc"
elif [ "$SHELL_NAME" = "bash" ]; then
  # bash: check for .bash_profile (macOS) or .bashrc (Linux/WSL)
  if [ -f "$HOME/.bash_profile" ]; then
    RCFILE="$HOME/.bash_profile"
  else
    RCFILE="$HOME/.bashrc"
  fi
elif [ "$SHELL_NAME" = "fish" ]; then
  RCFILE="$HOME/.config/fish/config.fish"
  ALIAS_LINE='alias portman="python3 ~/.portman/portman.py"'  # Fish has different syntax
else
  RCFILE="$HOME/.profile"
fi

# 3. Add alias if not already present
ALIAS_LINE='alias portman="python3 ~/.portman/portman.py"'
if grep -q "alias portman=" "$RCFILE" 2>/dev/null; then
  echo "  ℹ  portman alias already exists in $RCFILE"
else
  echo "" >> "$RCFILE"
  echo "# portman — port manager" >> "$RCFILE"
  echo "$ALIAS_LINE" >> "$RCFILE"
  echo "  ✓  Added alias to $RCFILE"
fi

echo ""
echo "  ✅  Done! Reload your shell with:"
echo "       source $RCFILE"
echo ""
echo "  Then try:"
echo "       portman new agentstack"
echo "       portman list"
echo "       portman dashboard"
echo ""
echo "  Engineered by Codermasky"
echo ""
