# AWS CLI Operations
# Utilities for AWS SSO authentication and credential management

version: '3'

tasks:
  default:
    desc: 'Show available AWS tasks'
    aliases: [help, h]
    silent: true
    cmds:
      - |
        # Color codes
        GREEN='\033[0;32m'
        YELLOW='\033[0;33m'
        BOLD='\033[1m'
        NC='\033[0m'

        echo -e "${BOLD}AWS CLI Operations${NC}"
        echo ""
        echo "Command                            Alias     Description                              Examples"
        echo "---------------------------------------------------------------------------------------------------"
        echo -e "${BOLD}Authentication:${NC}"
        echo -e "  ${GREEN}task aws:login${NC}                   ${YELLOW}l${NC}         Check and refresh AWS SSO credentials   PROFILE=my-profile"

  login:
    desc: 'Check AWS SSO credentials and refresh if needed'
    aliases: [l]
    silent: true
    vars:
      AWS_PROFILE: '{{.PROFILE | default .AWS_PROFILE}}'
    cmds:
      - |
        # Source secrets if .env has 1Password references
        if [ -f .env ] && grep -q "op://" .env 2>/dev/null; then
          TEMP_ENV=$(task op:export)
          source "$TEMP_ENV"
        elif [ -f .env ]; then
          # Load .env file if it exists (no op:// references)
          set -a
          source .env
          set +a
        fi

        # Use parameter, then environment variable, then .env value
        PROFILE="{{.AWS_PROFILE}}"
        if [ -z "$PROFILE" ]; then
          PROFILE="${AWS_PROFILE}"
        fi

        # Validate AWS_PROFILE is set
        if [ -z "$PROFILE" ]; then
          echo "Error: AWS_PROFILE not set"
          echo "Usage: task aws:login PROFILE=my-profile"
          echo "Or set AWS_PROFILE environment variable"
          echo "Or add AWS_PROFILE to .env file"
          exit 1
        fi

        # Check credentials and refresh if needed
        if ! AWS_PROFILE="$PROFILE" aws sts get-caller-identity &>/dev/null; then
          echo "AWS credentials expired or missing. Running SSO login..."
          aws sso login --profile "$PROFILE"
        fi
