#!/bin/bash
# Process a single crate and generate its debian/copyright.in.d/<crate> fragment
# Usage: process-crate.sh <crate-dir>

set -e

if [ $# -lt 1 ]; then
    echo "Usage: $0 <crate-dir>" >&2
    exit 1
fi

CRATE_DIR="$1"
CRATE=$(basename "$CRATE_DIR")
FRAGMENT_DIR="debian/copyright.in.d"
FRAGMENT="$FRAGMENT_DIR/$CRATE"

mkdir -p "$FRAGMENT_DIR"

# Check if stub
if debian/bin/is-stub.sh "$CRATE_DIR" 2>/dev/null; then
    touch "$FRAGMENT"
    echo "$CRATE: stub — created empty file"
    exit 0
fi

# Extract info from Cargo.toml
if [ ! -f "$CRATE_DIR/Cargo.toml" ]; then
    echo "Error: No Cargo.toml found in $CRATE_DIR" >&2
    exit 1
fi

# Parse Cargo.toml for license and repository
LICENSE=$(grep '^license = ' "$CRATE_DIR/Cargo.toml" | head -1 | sed 's/^license = "\(.*\)"$/\1/')
REPOSITORY=$(grep '^repository = ' "$CRATE_DIR/Cargo.toml" | head -1 | sed 's/^repository = "\(.*\)"$/\1/')
HOMEPAGE=$(grep '^homepage = ' "$CRATE_DIR/Cargo.toml" | head -1 | sed 's/^homepage = "\(.*\)"$/\1/')
NAME=$(grep '^name = ' "$CRATE_DIR/Cargo.toml" | head -1 | sed 's/^name = "\(.*\)"$/\1/')

# Determine source URL
if [ -n "$REPOSITORY" ]; then
    SOURCE="$REPOSITORY"
elif [ -n "$HOMEPAGE" ]; then
    SOURCE="$HOMEPAGE"
else
    SOURCE="https://crates.io/crates/$NAME"
fi

# Translate SPDX license to DEP-5
# First normalize separators and keywords
dep5_license=$(echo "$LICENSE" | \
    sed 's|/| OR |g' | \
    sed 's/ OR / or /g' | \
    sed 's/ AND / and /g' | \
    sed 's/MIT/Expat/g' | \
    sed 's/Apache-2\.0/Apache-2/g' | \
    sed 's/BSD-2-Clause/BSD-2-clause/g' | \
    sed 's/BSD-3-Clause/BSD-3-clause/g' | \
    sed 's/ WITH / with /g' | \
    sed 's/LLVM-exception/LLVM exception/g' | \
    sed 's/Unicode-DFS-2016/Unicode/g' | \
    sed 's/Unicode-3\.0/Unicode/g')

# Handle parentheses for compound expressions
# Convert (A or B) and C to A or B, and C
if echo "$dep5_license" | grep -q '(.*) and '; then
    dep5_license=$(echo "$dep5_license" | sed 's/(\([^)]*\)) and /\1, and /g')
fi
# Remove any remaining parentheses
dep5_license=$(echo "$dep5_license" | tr -d '()')

# Find license files
MIT_FILE=$(find "$CRATE_DIR" -maxdepth 1 -iname 'LICENSE-MIT' -o -iname 'LICENSE.MIT' 2>/dev/null | head -1)
APACHE_FILE=$(find "$CRATE_DIR" -maxdepth 1 -iname 'LICENSE-APACHE' -o -iname 'LICENSE.APACHE' 2>/dev/null | head -1)
UNLICENSE_FILE=$(find "$CRATE_DIR" -maxdepth 1 -iname 'UNLICENSE' 2>/dev/null | head -1)
COPYING_FILE=$(find "$CRATE_DIR" -maxdepth 1 -name 'COPYING' 2>/dev/null | head -1)

# Extract copyright from license files
copyright_year=""
copyright_holder=""

for lic_file in "$MIT_FILE" "$APACHE_FILE" "$COPYING_FILE"; do
    if [ -n "$lic_file" ] && [ -f "$lic_file" ]; then
        # Look for "Copyright (c) YEAR HOLDER" pattern
        copyright_line=$(grep -iE 'copyright \(c\) [0-9]{4}' "$lic_file" 2>/dev/null | head -1)
        if [ -n "$copyright_line" ]; then
            copyright_year=$(echo "$copyright_line" | grep -oE '[0-9]{4}' | head -1)
            copyright_holder=$(echo "$copyright_line" | sed -E 's/.*[0-9]{4}[- ]*(.*)$/\1/' | sed 's/^[[:space:]]*//')
            break
        fi
    fi
done

# If still empty, try to extract from files
if [ -z "$copyright_holder" ]; then
    # Look in source files
    copyright_line=$(grep -riE 'copyright \(c\) [0-9]{4}' "$CRATE_DIR" --include='*.rs' 2>/dev/null | head -1)
    if [ -n "$copyright_line" ]; then
        copyright_year=$(echo "$copyright_line" | grep -oE '[0-9]{4}' | head -1)
        copyright_holder=$(echo "$copyright_line" | sed -E 's/.*[0-9]{4}[- ]*(.*)$/\1/' | sed 's/^[[:space:]]*//')
    fi
fi

# If still empty, use authors from Cargo.toml
if [ -z "$copyright_holder" ]; then
    authors=$(grep '^authors = ' "$CRATE_DIR/Cargo.toml" 2>/dev/null | head -1 | sed 's/^authors = \["\(.*\)"\]$/\1/')
    if [ -n "$authors" ]; then
        copyright_holder="$authors"
    else
        copyright_holder="The $NAME authors"
    fi
fi

# Build copyright line
if [ -n "$copyright_year" ]; then
    copyright_line="$copyright_year $copyright_holder"
else
    copyright_line="$copyright_holder"
fi

# Start building the fragment
cat > "$FRAGMENT" <<EOF
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Source: $SOURCE

Files: debian/missing-sources/$CRATE/*
Copyright: $copyright_line
License: $dep5_license

EOF

# Add license texts based on what's needed
needs_expat=false
needs_apache2=false
needs_unlicense=false
needs_llvm_exception=false

if echo "$dep5_license" | grep -q "Expat"; then
    needs_expat=true
fi
if echo "$dep5_license" | grep -q "Apache-2"; then
    needs_apache2=true
fi
if echo "$dep5_license" | grep -q "Unlicense"; then
    needs_unlicense=true
fi
if echo "$dep5_license" | grep -q "LLVM exception"; then
    needs_llvm_exception=true
fi

# Add Expat license text
if [ "$needs_expat" = true ]; then
    cat >> "$FRAGMENT" <<'EOF'
License: Expat
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 .
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 .
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.

EOF
fi

# Add Apache-2 license pointer
if [ "$needs_apache2" = true ] && [ "$needs_llvm_exception" = false ]; then
    cat >> "$FRAGMENT" <<'EOF'
License: Apache-2
 On Debian systems, the full text of the Apache License version 2.0
 can be found in the file `/usr/share/common-licenses/Apache-2.0'.

EOF
elif [ "$needs_apache2" = true ] && [ "$needs_llvm_exception" = true ]; then
    cat >> "$FRAGMENT" <<'EOF'
License: Apache-2 with LLVM exception
 On Debian systems, the full text of the Apache License version 2.0
 can be found in the file `/usr/share/common-licenses/Apache-2.0'.
 .
 ---- LLVM Exceptions to the Apache 2.0 License ----
 .
 As an exception, if, as a result of your compiling your source code, portions
 of this Software are embedded into an Object form of such source code, you
 may redistribute such embedded portions in such Object form without complying
 with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
 .
 In addition, if you combine or link compiled forms of this Software with
 software that is licensed under the GPLv2 ("Combined Software") and if a
 court of competent jurisdiction determines that the patent provision (Section
 3), the indemnity provision (Section 9) or other Section of the License
 conflicts with the conditions of the GPLv2, you may retroactively and
 prospectively choose to deem waived or otherwise exclude such Section(s) of
 the License, but only in their entirety and only with respect to the Combined
 Software.

EOF
fi

# Add Unlicense text
if [ "$needs_unlicense" = true ]; then
    cat >> "$FRAGMENT" <<'EOF'
License: Unlicense
 This is free and unencumbered software released into the public domain.
 .
 Anyone is free to copy, modify, publish, use, compile, sell, or
 distribute this software, either in source code form or as a compiled
 binary, for any purpose, commercial or non-commercial, and by any
 means.
 .
 In jurisdictions that recognize copyright laws, the author or authors
 of this software dedicate any and all copyright interest in the
 software to the public domain. We make this dedication for the benefit
 of the public at large and to the detriment of our heirs and
 successors. We intend this dedication to be an overt act of
 relinquishment in perpetuity of all present and future rights to this
 software under copyright law.
 .
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 .
 For more information, please refer to <http://unlicense.org/>

EOF
fi

echo "$CRATE: $dep5_license — generated"
