#!/bin/bash
#
# MBARI License Initialization Script
# This script helps set up proper licensing for MBARI repositories
#
# Usage: ./init-license.sh [license-type]
# license-type: apache2, mit, bsd3, or interactive (default)

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CURRENT_YEAR=$(date +%Y)

print_header() {
    echo -e "${BLUE}================================================${NC}"
    echo -e "${BLUE}  MBARI Software License Initialization${NC}"
    echo -e "${BLUE}================================================${NC}"
    echo ""
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

# Check if we're in a git repository
check_git_repo() {
    if ! git rev-parse --git-dir > /dev/null 2>&1; then
        print_error "Not in a git repository. Please run 'git init' first."
        exit 1
    fi
}

# Interactive license selection
interactive_selection() {
    echo -e "${BLUE}License Selection Decision Tree${NC}"
    echo ""
    
    read -p "Does this project contain ITAR/EAR restricted technology? (y/n): " itar
    if [[ $itar == "y" ]]; then
        print_warning "ITAR/EAR restricted projects must remain PRIVATE."
        print_warning "Do NOT add a public license. Contact legal before any release."
        exit 0
    fi
    
    read -p "Does this project have an existing commercial license agreement? (y/n): " commercial
    if [[ $commercial == "y" ]]; then
        print_warning "Contact tech transfer office for guidance on dual-licensing."
        exit 0
    fi
    
    read -p "Is this a collaborative project with external partners? (y/n): " collab
    if [[ $collab == "y" ]]; then
        print_warning "Consider matching partner's license or discussing Apache 2.0."
        read -p "Do you want to proceed with Apache 2.0? (y/n): " proceed
        if [[ $proceed != "y" ]]; then
            echo "Please coordinate with partners on license selection."
            exit 0
        fi
        LICENSE_TYPE="apache2"
    else
        read -p "Do you want derivatives to remain open-source (copyleft)? (y/n): " copyleft
        if [[ $copyleft == "y" ]]; then
            print_warning "Consider GPL-3.0 or AGPL-3.0 for copyleft protection."
            echo "This script handles permissive licenses. Please manually add GPL."
            exit 0
        fi
        
        read -p "Is this a simple utility or small library? (y/n): " simple
        if [[ $simple == "y" ]]; then
            echo ""
            echo "For simple projects, you can use:"
            echo "  1) Apache 2.0 (default, includes patent grant)"
            echo "  2) MIT (simpler, widely used)"
            read -p "Choose (1/2): " choice
            if [[ $choice == "2" ]]; then
                LICENSE_TYPE="mit"
            else
                LICENSE_TYPE="apache2"
            fi
        else
            print_success "Using Apache 2.0 (MBARI default)"
            LICENSE_TYPE="apache2"
        fi
    fi
}

# Copy license file
copy_license() {
    local license=$1
    local license_file=""
    
    case $license in
        apache2)
            license_file="${SCRIPT_DIR}/LICENSE-Apache-2.0"
            license_name="Apache License 2.0"
            spdx_id="Apache-2.0"
            ;;
        mit)
            license_file="${SCRIPT_DIR}/LICENSE-MIT"
            license_name="MIT License"
            spdx_id="MIT"
            ;;
        bsd3)
            license_file="${SCRIPT_DIR}/LICENSE-BSD-3-Clause"
            license_name="BSD 3-Clause License"
            spdx_id="BSD-3-Clause"
            ;;
        *)
            print_error "Unknown license type: $license"
            exit 1
            ;;
    esac
    
    if [[ ! -f "$license_file" ]]; then
        print_error "License template not found: $license_file"
        exit 1
    fi
    
    # Copy and update year
    sed "s/\[year\]/$CURRENT_YEAR/g" "$license_file" > LICENSE
    print_success "Created LICENSE file with $license_name"
    
    # Export for later use
    export LICENSE_NAME="$license_name"
    export SPDX_ID="$spdx_id"
}

# Update README if it exists
update_readme() {
    if [[ -f "README.md" ]]; then
        if grep -q "## License" README.md; then
            print_warning "README.md already has a License section"
        else
            echo "" >> README.md
            echo "## License" >> README.md
            echo "" >> README.md
            echo "This project is licensed under the $LICENSE_NAME - see the [LICENSE](LICENSE) file for details." >> README.md
            echo "" >> README.md
            echo "Copyright (c) $CURRENT_YEAR Monterey Bay Aquarium Research Institute" >> README.md
            print_success "Added license section to README.md"
        fi
    else
        print_warning "No README.md found. Consider adding one with license information."
    fi
}

# Create source file header examples
create_header_examples() {
    cat > .license-headers.txt << EOF
# License Header Examples

## Python
# Copyright (c) $CURRENT_YEAR Monterey Bay Aquarium Research Institute
# SPDX-License-Identifier: $SPDX_ID

## Java/C++/JavaScript
// Copyright (c) $CURRENT_YEAR Monterey Bay Aquarium Research Institute
// SPDX-License-Identifier: $SPDX_ID

## Shell/Bash
# Copyright (c) $CURRENT_YEAR Monterey Bay Aquarium Research Institute
# SPDX-License-Identifier: $SPDX_ID

## HTML/XML
<!-- Copyright (c) $CURRENT_YEAR Monterey Bay Aquarium Research Institute -->
<!-- SPDX-License-Identifier: $SPDX_ID -->
EOF
    print_success "Created .license-headers.txt with examples"
}

# Main script
main() {
    print_header
    check_git_repo
    
    # Check if LICENSE already exists
    if [[ -f "LICENSE" ]]; then
        print_warning "LICENSE file already exists"
        read -p "Do you want to replace it? (y/n): " replace
        if [[ $replace != "y" ]]; then
            echo "Exiting without changes."
            exit 0
        fi
    fi
    
    # Determine license type
    if [[ $# -eq 1 ]]; then
        LICENSE_TYPE=$1
    else
        interactive_selection
    fi
    
    # Apply license
    copy_license "$LICENSE_TYPE"
    update_readme
    create_header_examples
    
    echo ""
    print_success "License initialization complete!"
    echo ""
    echo "Next steps:"
    echo "  1. Review the LICENSE file"
    echo "  2. Update README.md if needed"
    echo "  3. Consider adding license headers to source files (see .license-headers.txt)"
    echo "  4. Commit and push: git add LICENSE README.md && git commit -m 'Add license'"
    echo ""
    echo "Documentation: https://github.com/mbari-org/.github/blob/main/LICENSING.md"
}

# Run main function
main "$@"
