#!/bin/bash
set -euo pipefail

if [[ $# -ne 1 ]]; then
  echo "❌ Usage: $0 <repo-name>"
  exit 1
fi

REPO_NAME="$1"
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COMMON_FILE="$ROOT_DIR/woodpecker.common.yml"
CUSTOM_FILE="$ROOT_DIR/$REPO_NAME/woodpecker.custom.yml"
OUTPUT_FILE="$ROOT_DIR/$REPO_NAME/.woodpecker.yml"

# ✅ Vérification des fichiers sources
if [[ ! -f "$COMMON_FILE" ]]; then
  echo "❌ Missing common pipeline file: $COMMON_FILE"
  exit 1
fi

if [[ ! -f "$CUSTOM_FILE" ]]; then
  echo "❌ Missing custom pipeline file: $CUSTOM_FILE"
  exit 1
fi

# 🧹 Nettoyage de l’ancien fichier
rm -f "$OUTPUT_FILE"

echo "🔧 Generating pipeline for '$REPO_NAME'..."
echo "   → Common : $COMMON_FILE"
echo "   → Custom : $CUSTOM_FILE"
echo "   → Output : $OUTPUT_FILE"
echo

# --- Début du document YAML
echo "---" > "$OUTPUT_FILE"

# Ajouter la partie avant `steps:`
grep -B9999 '^steps:' "$COMMON_FILE" | grep -v '^steps:' >> "$OUTPUT_FILE"

# Fusion des steps
echo "steps:" >> "$OUTPUT_FILE"

awk '
  /^steps:/ {capture=1; next}
  capture && /^[^[:space:]]/ {capture=0}
  capture {print}
' "$COMMON_FILE" >> "$OUTPUT_FILE"

awk '
  /^steps:/ {capture=1; next}
  capture && /^[^[:space:]]/ {capture=0}
  capture {print}
' "$CUSTOM_FILE" >> "$OUTPUT_FILE"

# 🧽 Nettoyage des listes YAML dans [ ... ]
echo "🧽 Cleaning YAML list syntax (brackets only)..."

PERL_SCRIPT="$(mktemp)"
cat <<'EOF' > "$PERL_SCRIPT"
use strict;
use warnings;
undef $/;

my $file = shift;
open my $fh, '<', $file or die "Cannot read $file: $!";
my $content = <$fh>;
close $fh;

$content =~ s{
  \[(.*?)\]
}{
  my $list = $1;
  my @items = grep { length } split /\s*,\s*|\s+/, $list;
  "[" . join(", ", @items) . "]";
}gsxe;

open my $out, '>', $file or die "Cannot write $file: $!";
print $out $content;
close $out;
EOF

perl "$PERL_SCRIPT" "$OUTPUT_FILE"
rm -f "$PERL_SCRIPT"

# 📏 Repli des longues lignes de commande (> 80 chars)
echo "🧼 Folding long command lines (> 80 chars)..."

PERL_SCRIPT_2="$(mktemp)"
cat <<'EOF' > "$PERL_SCRIPT_2"
use strict;
use warnings;

my $file = shift;
open my $in, '<', $file or die "Cannot read $file: $!";
my @lines = <$in>;
close $in;

open my $out, '>', $file or die "Cannot write $file: $!";

my $in_commands = 0;
my $commands_indent = '';

foreach my $line (@lines) {
  if ($line =~ /^(\s*)commands:\s*$/) {
    $in_commands = 1;
    $commands_indent = $1;
    print $out $line;
    next;
  }

  if ($in_commands && $line !~ /^$commands_indent\s{2,}/) {
    $in_commands = 0;
  }

  if ($in_commands && $line =~ /^(\s*)-\s+(.*)$/ && length($2) > 80) {
    print $out "$1- >\n";
    print $out "$1  $2\n";
  } else {
    print $out $line;
  }
}

close $out;
EOF

perl "$PERL_SCRIPT_2" "$OUTPUT_FILE"
rm -f "$PERL_SCRIPT_2"

# 🧪 Validation YAML
echo "🧪 Validating YAML syntax..."

if ! command -v yamllint &>/dev/null; then
  echo "⚠️ yamllint not found. Attempting to install..."

  if [[ -f /etc/alpine-release ]]; then
    echo "📦 Installing yamllint via apk..."
    apk add --no-cache yamllint || { echo "❌ Failed to install yamllint"; exit 1; }
  elif [[ -f /etc/debian_version ]]; then
    echo "📦 Installing yamllint via apt..."
    sudo apt update && sudo apt install -y yamllint || { echo "❌ Failed to install yamllint"; exit 1; }
  else
    echo "❌ Unsupported system. Please install yamllint manually."
    exit 1
  fi
fi

yamllint "$OUTPUT_FILE"
if [[ $? -ne 0 ]]; then
  echo "❌ YAML validation failed"
  exit 1
else
  echo "✅ YAML validation passed"
fi