#!/bin/bash
# Debrepack, pack a structured folder into a Debian Package.
# Concept and testing by Glen MacArthur, coded by Google Gemini 3.
# Based on a 2011 'Deb-Builder' Zenity script by Tony Brijeski.

TARGET_DIR=$(realpath "$1")
PARENT_DIR=$(dirname "$TARGET_DIR")
PKG_NAME=$(basename "$TARGET_DIR")
ICON="/usr/local/share/icons/custom/debrepack.png"
IMAGE="/usr/local/share/icons/custom/debrepack-app.png"
LOG="/tmp/debrepack.log"

if [ ! -d "$TARGET_DIR/DEBIAN" ]; then
    yad --error --center --text="No DEBIAN folder found in $PKG_NAME"
    exit 1
fi

pkexec bash -c "
    exec > '$LOG' 2>&1
    cd '$PARENT_DIR'
    
    # 1. Reconstruct Control File
    CONTROL='$PKG_NAME/DEBIAN/control'
    NEW_CONTROL='\$CONTROL.new'
    INTERNAL_NAME=\$(grep '^Package:' \"\$CONTROL\" | cut -d: -f2 | xargs)
    VERSION=\$(grep '^Version:' \"\$CONTROL\" | cut -d: -f2 | xargs)
    MAINTAINER=\$(grep '^Maintainer:' \"\$CONTROL\" | cut -d: -f2 | xargs)
    
    > \"\$NEW_CONTROL\"
    while IFS= read -r line; do
        field=\$(echo \"\$line\" | cut -d: -f1 | xargs)
        [[ -z \"\$field\" ]] && continue
        [[ \"\$field\" == \"Installed-Size\" ]] && continue
        if ! grep -qi \"^\$field:\" \"\$NEW_CONTROL\"; then
            echo \"\$line\" | sed 's/[[:space:]]*$//' >> \"\$NEW_CONTROL\"
        fi
    done < \"\$CONTROL\"

    # 2. Doc Reconstruction (The tar.gz/gzip logic)
    DOC_DIR=\"$PKG_NAME/usr/share/doc/\$INTERNAL_NAME\"
    mkdir -p \"\$DOC_DIR\"

    # Create a basic copyright if it doesn't exist
    if [ ! -f \"\$DOC_DIR/copyright\" ]; then
        echo \"Copyright \$(date +%Y) \$MAINTAINER\" > \"\$DOC_DIR/copyright\"
    fi

    # Create/Gzip the Changelog (standard Debian practice)
    cat > \"\$DOC_DIR/changelog.Debian\" <<EOF
\$INTERNAL_NAME (\$VERSION) unstable; urgency=low
  * Repacked by debrepack utility.
 -- \$MAINTAINER  \$(date -R)
EOF
    gzip -9fn \"\$DOC_DIR/changelog.Debian\"

    # 3. Permissions & Ownership
    chown -R root:root '$PKG_NAME'
    find '$PKG_NAME' -type d -exec chmod 755 {} +
    find '$PKG_NAME' -type f ! -executable -exec chmod 644 {} +
    [ -d '$PKG_NAME/DEBIAN' ] && find '$PKG_NAME/DEBIAN' -type f ! -name 'control' ! -name 'md5sums' -exec chmod 755 {} +
    find '$PKG_NAME' -type f \( -path '*/bin/*' -o -path '*/sbin/*' -o -name '*-bin' \) -exec chmod 755 {} +

    # 4. Finalize Control
    SIZE=\$(du -s '$PKG_NAME' | awk '{print \$1}')
    echo \"Installed-Size: \$SIZE\" >> \"\$NEW_CONTROL\"
    sed -i -e '\$a\' \"\$NEW_CONTROL\"
    mv \"\$NEW_CONTROL\" \"\$CONTROL\"
    chmod 644 \"\$CONTROL\"

    # 5. Build
    dpkg-deb --build '$PKG_NAME'
"

if [ $? -eq 0 ]; then
    yad --info --center --width=400 --title="Repack Successful!" \
        --image="$IMAGE" --window-icon="$ICON" --text="<b>$PKG_NAME.deb</b>\nBuilt successfully!." --timeout=4
else
    yad --error --center --width=600 --height=300 --title="Build Failed" \
        --window-icon="$ICON" --text-info --filename="$LOG"
fi