#!/bin/sh
set -eu

# Extract Homepage field from debian/control
homepage=$(grep -E '^Homepage:' debian/control | awk '{print $2}')

# Make sure it's a GitHub URL
case "$homepage" in
  https://github.com/*/*)
    owner=$(echo "$homepage" | cut -d/ -f4)
    project=$(echo "$homepage" | cut -d/ -f5)
    ;;
  *)
    echo "Warning: Homepage is not a GitHub URL: $homepage" >&2
    watch=$(grep -o 'https://github.com/[^/]\+/[^[:space:]]*' debian/watch | sed 's/\.git//')
    case "$watch" in
      https://github.com/*/*)
        owner=$(echo "$watch" | cut -d/ -f4)
        project=$(echo "$watch" | cut -d/ -f5)
        ;;
    *)
        echo "Error: watch file is not pointing to GitHub: $homepage" >&2
        exit 1
        ;;
    esac
    ;;
esac

use_tags=0

response=$(curl -s -o /dev/null -w "%{http_code}" "https://api.github.com/repos/$owner/$project/tags")

if [ "$response" -eq 200 ]; then
    # Check if tags array is not empty
    tag_count=$(curl -s "https://api.github.com/repos/$owner/$project/tags" | jq length 2>/dev/null || echo "0")
    
    if [ "$tag_count" -gt 0 ]; then
        echo "Repository has $tag_count tags"
        use_tags=1
    else
        echo "Repository exists but has no tags"
    fi
elif [ "$response" -eq 301 ]; then
    echo "Repository moved permanently.  Please adjust Homepage field."
    exit 1
elif [ "$response" -eq 404 ]; then
    echo "Repository not found"
    exit 1
else
    echo "Error: HTTP $response"
    exit 1
fi

cat > debian/watch <<EOF
Version: 5

EOF

if [ $use_tags -eq 1 ] ; then
cat >> debian/watch <<EOF
Template: Github
Owner: $owner
Project: $project
EOF
else
# Append to debian/watch
cat >> debian/watch <<EOF
Source: https://github.com/$owner/$project.git
Matching-Pattern: HEAD
Mode: git
Git-Pretty: 0.0~git%cd.%h
EOF
fi
