#!/bin/bash

set -e

# Populate configuration variables. First check for a pre-existing environment
# variable which we support; that should override the configuration variable,
# which in turn overrides the default. Some configuration variables are only
# allowed in ~/.dpatch.conf, some only in debian/patches/00dpatch.conf.

# CLI option parsing comes later, and
# will blindly set it to the option given therein; CLI options trump all.

# Defining these vaiables here, allows users to set e.g.
# conf_origtargzpath="/usr/local/src/packages/${PACKAGENAME}"
PACKAGENAME="$(dpkg-parsechangelog | sed -n '/^Source:/{s/^Source:[[:space:]]\+\(.*\)/\1/;p;q}')"
UPSTREAMVERSION="$(dpkg-parsechangelog | sed -n '/^Version:/{s/^Version:[[:space:]]\+\([0-9]\+:\)\?\([^-]\+\).*/\2/;p;q}')"

# Read in the package's configuration file, should it exist.
[[ -f debian/patches/00dpatch.conf ]] && . debian/patches/00dpatch.conf
unset conf_sourcedir
unset conf_outdir
unset conf_clean
DPEP_DEBIANONLY="${DPEP_DEBIANONLY:-${conf_debianonly:-}}"
unset conf_newdesc
unset conf_keeptemp
unset conf_tmpdir
unset conf_shell
unset conf_stampdir

# Read in the user's configuration file, should it exist.
[[ -f ~/.dpatch.conf ]] && . ~/.dpatch.conf

DPEP_SOURCEDIR="${DPEP_SOURCEDIR:-${conf_sourcedir:-$(pwd)}}"
DPEP_OUTDIR="${DPEP_OUTDIR:-${conf_outdir:-$DPEP_SOURCEDIR/debian/patches}}"
DPEP_STAMPDIR="${DPEP_STAMPDIR:-${conf_stampdir:-$DPEP_SOURCEDIR/debian/patched}}"
DPEP_CLEAN="${DPEP_CLEAN:-${conf_clean:-}}"
DPEP_ORIGTARGZ="${DPEP_ORIGTARGZ:-${conf_origtargz:-}}"
DPEP_GETORIGTARGZ="${DPEP_GETORIGTARGZ:-${conf_getorigtargz:-dpatch-get-origtargz}}"
DPEP_DESC="${DPEP_NEWDESC:-${conf_newdesc:-No description.}}"
DPEP_KEEPTEMP="${DPEP_KEEPTEMP:-${conf_keeptemp:-0}}"
DPEP_TMPDIR="${DPEP_TMPDIR:-${conf_tmpdir:-${TMPDIR:-/tmp}}}"
DPEP_SHELL="${DPEP_SHELL:-${conf_shell:-${SHELL:-$(getent passwd $(id -un) | cut -f7- -d:)}}}"
DPEP_EXCLUDE="${DPEP_EXCLUDE:-${conf_exclude:-CVS .svn .git .arch .hg _darcs .bzr .ilist}}"
DPEP_ORIGTARGZPATH="${DPEP_ORIGTARGZPATH:-${conf_origtargzpath:-}}"
DPEP_COWCMD="${DPEP_COWCMD:-${conf_cowcmd:-}}"

# We special-case $DPEP_ROOTCMD later, after dpep_parse_options()

VERBOSITY=0

# Import functions dpep_usage(), dpep_template(), dpep_parse_options(),
# dpep_message(), dpep_parse_longopt_value() 
. /usr/share/dpatch/dpatch-edit-patch.functions

dpep_parse_options "$@" || true

# We special-case $DPEP_ROOTCMD here; if fakeroot doesn't exist and we haven't
# been told explicitly what it should be, error out. (I refuse to use sudo as
# any kind of default, even a fallback if fakeroot doesn't exist - way too
# dangerous). We do this after option parsing, to ensure that they can supply a
# ROOTCMD on the CLI.
if [[ -z "$DPEP_ROOTCMD" ]]; then
    # We're only here if $DPEP_ROOTCMD hasn't already been set via either a CLI
    # argument or the environment variable itself.
    if [[ ! -z "$conf_rootcmd" ]]; then
	# If we're here, the configuration variable has been set
	DPEP_ROOTCMD="$conf_rootcmd"
    elif command -v fakeroot > /dev/null 2>&1; then
	# If we're here, nothing's been set, but fakeroot exists.
	DPEP_ROOTCMD="fakeroot"
    else
	# We're here, nothing's set, fakeroot's not found. Bail.
	dpep_message error " "
	printf "fakeroot is not installed, nor has the option --rootcmd been given, nor has the\n"
	printf "environment variable \$DPEP_ROOTCMD been set, nor has the configuration file\n"
	printf "variable conf_rootcmd been set. Please see the manual page for more details.\n"
	exit 1
    fi
fi

# We special-case $DPEP_COWCMD here; We _ought_ to be switching behaviour
# instead. We do this after option parsing, to ensure that they can supply
# a COWCMD on the CLI.
if [[ -z "$DPEP_COWCMD" ]]; then
    # We're only here if $DPEP_COWCMD hasn't already been set via either a CLI
    # argument or the environment variable itself.
    if [[ ! -z "$conf_rootcmd" ]]; then
	# If we're here, the configuration variable has been set
	DPEP_COWCMD="$conf_rootcmd"
    elif command -v fakeroot > /dev/null 2>&1; then
	# If we're here, nothing's been set, but fakeroot exists.
	DPEP_COWCMD="cow-shell"
    else
	# We're here, nothing's set, cow-shell's not found. Bail.
	dpep_message error " "
	printf "cow-shell is not installed, nor has the option --cowcmd been given, nor has the\n"
	printf "environment variable \$DPEP_COWCMD been set, nor has the configuration file\n"
	printf "variable conf_cowcmd been set. Please see the manual page for more details.\n"
	exit 1
    fi
fi

# All argument and option parsing has been done. Time to accomplish something.
# Change to source directory
cd "$DPEP_SOURCEDIR"

# $PWD: $DPEP_SOURCEDIR
if [[ ! -e "debian/rules" ]]; then
# Check to make sure we're in the toplevel directory of a Debian package;
# if not, error out.
    dpep_message error "\"$DPEP_SOURCEDIR\" is not the toplevel directory of a Debian package, aborting."
    exit 1
fi

# Source 00options, currently known options are DPATCH_OPTION_CPP
# and DPEP_OPTION_EXEC_TEMPLATE
[ -r "debian/patches/00options" ] && . debian/patches/00options

# Check to see $DPEP_PATCH is empty, and fail now.
if [[ "${DPEP_PATCH}" = "" ]]; then
    # If it doesn't have .dpatch, append it.
    dpep_message error "patchname is empty, please specify, aborting."
    exit 1
fi

# Check to see whether or not $DPEP_PATCH ends with .dpatch
if [[ "${DPEP_PATCH}" = "${DPEP_PATCH%%.dpatch}" ]]; then
    # If it doesn't have .dpatch, append it.
    DPEP_PATCH="${DPEP_PATCH}.dpatch"
fi

# $PWD: $DPEP_SOURCEDIR
if [[ -e "$DPEP_OUTDIR/$DPEP_PATCH" ]]; then
# Check to see if the patch we're told to edit exists; if not, we'll be
# creating it.
    # The patch does already exist, let them know this.
    dpep_message norm "* $DPEP_OUTDIR/$DPEP_PATCH exists, this patch will be updated."
    # Also set this ... later on, we'll need to differentiate between editing
    # an existing patch, and creating a new one.
    DPEP_EDITPATCH=1
    if [[ ! -z "$DPEP_BASEPATCH" ]]; then
	# Even though we're editing an already-existing patch, the user has
	# supplied a base-patch. Warn them that we will be ignoring this.
	dpep_message warn "We are editing an already-existing patch, but a base-patch of $DPEP_BASEPATCH has been supplied - ignoring."
	# We patch up to $DPEP_BASEPATCH in the workdir later, so we assign to
	# it the patch we'll be editing
	DPEP_BASEPATCH="$DPEP_PATCH"
    else
	# They haven't supplied a base-patch, which is nice and sane, so we
	# assign to it the patch we'll be editing, for the same reason as
	# above; we'll be applying it to the working directory.
	DPEP_BASEPATCH="$DPEP_PATCH"
    fi
else
    # Patch doesn't exist, we aren't editing it.
    DPEP_EDITPATCH=0
    dpep_message norm "* $DPEP_OUTDIR/$DPEP_PATCH does not exist, it will be created as a new dpatch."
    # Check to ensure that, if we've been given a base-patch, it exists;
    # otherwise we really need to abort. If we haven't been supplied one,
    # that's fine
    if [[ ! -z "$DPEP_BASEPATCH" ]]; then
	if [[ "$DPEP_BASEPATCH" = "${DPEP_BASEPATCH%%.dpatch}" ]]; then
	    # The user didn't supply a .dpatch extension, so we supply it.
	    DPEP_BASEPATCH="$DPEP_BASEPATCH.dpatch"
	fi
	if [[ ! -e "debian/patches/$DPEP_BASEPATCH" ]]; then
	    dpep_message error "Base-patch $(pwd)/debian/patches/$DPEP_BASEPATCH does not exist, aborting."
	fi
    fi
fi

# built appropriate options for tar and diff to exclude files
# is DPEP_EXCLUDE is empty, this will be empty as well.
DPEP_TAR_EXCLUDE="$(echo $DPEP_EXCLUDE | sed 's/\([^[:space:]]\+\)/--exclude \1/g')"
DPEP_DIFF_EXCLUDE="$(echo $DPEP_EXCLUDE | sed 's/\([^[:space:]]\+\)/--exclude=\1/g')"

# Start preparing the working copy.
# $PWD: $DPEP_SOURCEDIR
# Sanity checking to ensure that our temporary directory exists and is
# writable.
if [[ ! -d "$DPEP_TMPDIR" ]]; then
    dpep_message error "Temporary directory $DPEP_TMPDIR does not exist, aborting."
    exit 1
elif [[ ! -w "$DPEP_TMPDIR" ]]; then
    dpep_message error "Temporary directory $DPEP_TMPDIR is not writable, aborting."
    exit 1
fi

# $PWD: $DPEP_SOURCEDIR
# Hopefully mktemp(1), part of debianutils, does the Right Thing :) We're
# pretty sure it does :)
WORKDIR="$(TMPDIR=$DPEP_TMPDIR mktemp -d -p /tmp dpep-work.XXXXXX)"
dpep_message debug1 "Working directory is $WORKDIR"

if [ -n "$DPEP_CLEAN" ]; then
    REFDIR="$DPEP_SOURCEDIR"
    dpep_message debug1 "Using source directory $DPEP_SOURCEDIR as reference directory"
else
    if [ -f "$DPEP_STAMPDIR/$DPEP_PATCH" ]; then
	dpep_message error "Patch $DPEP_PATCH is applied on working directory, use --clean option"
	exit 1
    fi
    REFPDIR="$(TMPDIR=$DPEP_TMPDIR mktemp -d -p /tmp dpep-ref.XXXXXX)"
    dpep_message debug1 "Reference directory is $REFPDIR"
    if [ -n "$DPEP_DEBIANONLY" ]; then
        dpep_message norm "* debian/-only layout selected"
	if [ -z "$DPEP_ORIGTARGZ" ]; then
            ORIGTARGZ="${PACKAGENAME}_${UPSTREAMVERSION}.orig.tar.gz"
	    export DPGO_ORIGTARGZPATH="$DPEP_ORIGTARGZPATH"
	    if ! eval "$DPEP_GETORIGTARGZ $REFPDIR"; then
	        dpep_message error "unable to obtain upstream tarball, $DPEP_GET_ORIGTARGZ failed"
		exit 1
	    fi
	else
	    if [ -e "$DPEP_ORIGTARGZ" ]; then
		ORIGTARGZ="$(readlink -f "$DPEP_ORIGTARGZ")"
	    else
		dpep_message error "$DPEP_ORIGTARGZ, given on command line, does not exist"
		exit 1
	    fi
	fi
	cd "$REFPDIR"
	dpep_message norm "* unpacking $ORIGTARGZ"
	tar --extract --gzip --file $ORIGTARGZ
	# this heuristic is stolen from dpkg-source
	if [ "$(find . -maxdepth 1 -mindepth 1 -type d -print | wc -l)" -eq 1 ]; then
	  if [ "$(readlink -f "$(find . -maxdepth 1 -mindepth 1 -type d -print)")" != "$(readlink -f "$(basename "$DPEP_SOURCEDIR")")" ]; then
	    mv "$(find . -maxdepth 1 -mindepth 1 -type d -print)" "$(basename "$DPEP_SOURCEDIR")"
	  fi
	else
	  mkdir "$(basename "$DPEP_SOURCEDIR")"
	  find . -maxdepth 1 -mindepth 1 -type d -name "$(basename "$DPEP_SOURCEDIR")" -prune -o -print0 | \
	    xargs --null mv --target-directory="$(basename "$DPEP_SOURCEDIR")"
	fi
    fi
    cd "$REFPDIR"
    dpep_message norm "* Hardlinking $DPEP_SOURCEDIR to reference directory."
    cp --archive --link "$DPEP_SOURCEDIR" $(basename "$DPEP_SOURCEDIR")
    if [ -n "$DPEP_CLEAN" ]; then
    	# Remove the files from the working directory that we don't want to be part of the diff
    	for igfile in "$DPEP_EXCLUDE"; do find $(basename "$DPEP_SOURCEDIR") -name "$igfile" -print0; done | xargs -0 -r rm -r
    fi
    REFDIR="$REFPDIR/$(basename $DPEP_SOURCEDIR)"
fi    
cd "$REFDIR"

# $PWD: reference directory
# Copy, clean, and clone $DPEP_SOURCEDIR
dpep_message norm "* Cleaning $REFDIR"
$DPEP_COWCMD $DPEP_ROOTCMD debian/rules clean unpatch
export COWDANCER_REUSE=yes
$DPEP_COWCMD dpatch deapply-all

if [[ ! -z "$DPEP_BASEPATCH" ]]; then
    if ! dpatch list-all | grep -F "${DPEP_BASEPATCH%%.dpatch}" > /dev/null 2>&1; then
	if [[ "$DPEP_EDITPATCH" = 1 ]]; then
	    dpep_message warn "$DPEP_PATCH is not listed in debian/patches/00list, no other patches will be applied to the working directory."
	else
	    dpep_message error "Base-patch is not listed in debian/patches/00list, aborting."
	    exit 1
	fi
    else
	dpep_message norm "* Applying patches"
	if [ "$DPEP_EDITPATCH" = 1 ]; then
	    DPEP_apply_until="$(dpatch list-all | grep -B1 -F "${DPEP_PATCH%%.dpatch}" | head -n 1)"
	    # Check below to see if our "apply-until" patch is the same as
	    # the one we're editing. If it is, it happens to be the first in
	    # 00list. That's a bug, we'll hack around it by explicitly
	    # checking for it, and if we find it, we'll do nothing here
	    if [ ! "$DPEP_apply_until" = "${DPEP_PATCH%%.dpatch}" ]; then
		$DPEP_COWCMD dpatch apply-until "$DPEP_apply_until"
	    fi
	else
	    $DPEP_COWCMD dpatch apply-until "${DPEP_BASEPATCH%%.dpatch}"
	fi
    fi
else
    dpep_message warn "* No base-patch supplied, not applying any patches."
fi

export COWDANCER_REUSE=no
dpep_message norm "* Hard linking directory $REFDIR to work directory."
cd "$WORKDIR"
cp --archive --link "$REFDIR" $(basename "$DPEP_SOURCEDIR")
if [ -n "$DPEP_CLEAN" ]; then
	# Remove the files from the working directory that we don't want to be part of the diff
	for igfile in "$DPEP_EXCLUDE"; do find $(basename "$DPEP_SOURCEDIR") -name "$igfile" -print0; done | xargs -0 -r rm -r
fi

# Change to the workdirectory, apply the patch we're editing if we're
# editing one, and launch an interactive shell.
cd "$WORKDIR/$(basename "$DPEP_SOURCEDIR")"
if [[ "$DPEP_EDITPATCH" = "1" ]]; then
    dpep_message norm "* Applying current $DPEP_PATCH for editing."
    if ! dpatch apply --no-stamp "$DPEP_PATCH"; then
       dpep_message warn "Could not apply the patch we want to edit -- not aborting, as you may want to work with the .rejs."
    fi
fi
cat <<EOF

$(basename $0):

Now launching an interactive shell in your work directory. Edit your files.
When you are done, exit the shell. When you exit the shell, your patch will be
automatically updated based on the changes in your work directory.

If you wish to abort the process, exit the shell such that it returns an exit
code of "230". This is typically done by exiting the shell with the command
'exit 230'.
EOF
$DPEP_COWCMD $DPEP_SHELL && EXITVAL=0 || EXITVAL="$?"
if [[ "$EXITVAL" = "230" ]]; then
    dpep_message error "Shell exited with an exit value of 230, aborting."
    dpep_cleanup
    exit 1
elif [[ "$EXITVAL" != "0" ]]; then
    dpep_message warn "Shell exited with an exit value other than 0."
fi
cd "$WORKDIR"

# Okay, they've exited the shell in a reasonable manner, and as such we're
# free to create or update the patch.
DIFFHOLDER="$(tempfile -d "$WORKDIR" -p "dpep." -s ".diff")"
dpep_message debug1 "Diff temporary file is $DIFFHOLDER"
cd "$REFDIR"
LC_ALL=C diff -urNad $DPEP_DIFF_EXCLUDE . "$WORKDIR/$(basename "$DPEP_SOURCEDIR")" |
  sed -e "/^--- \|^diff /s: \./: $(basename "$DPEP_SOURCEDIR")~/:" \
      -e "/^+++ \|^diff /s: $WORKDIR/: :" \
      -e "/^diff /s: $DPEP_DIFF_EXCLUDE::" > "$DIFFHOLDER" || true

# Diff created, let's switch back to the original directory, and start the
# process of updating or creating the patch.
cd "$DPEP_SOURCEDIR"
if [[ "$DPEP_EDITPATCH" = "0" ]]; then
    # We're creating a new patch, so this is relatively easy.
    dpep_message norm "* Creating new patch $DPEP_OUTDIR/$DPEP_PATCH"
    # We don't know for sure that any directories are created, so let's create
    # them now.

    PATCHDIR="$DPEP_OUTDIR/$(dirname "$DPEP_PATCH")"
    NEWPATCH="$DPEP_OUTDIR/$DPEP_PATCH"

    [[ ! -d "$PATCHDIR" ]] && mkdir -p "$PATCHDIR"
    if [[ ! -e "debian/patches/00template" ]]; then
	dpep_message warn "debian/patches/00template not exist, using hardcoded default."
	dpep_template_hardcoded "$NEWPATCH" "$NEWPATCH" "$DPEP_DESC"
    else
	dpep_message norm "Using debian/patches/00template"
	dpep_template_apply "$NEWPATCH" "$DPEP_DESC"
    fi
    # Okay, headers and shell snippets all set up. Now copy the actual patch text.
    cat "$DIFFHOLDER" >> "$NEWPATCH"
    dpep_message norm "$NEWPATCH created."
else
    # Damnit, we're editing a patch. This is _never_ fun :)
    OLDPATCH="$DPEP_OUTDIR/$DPEP_PATCH"
    dpep_message norm "Updating patch $OLDPATCH"
    # Need another temporary file.
    NEWPATCH="$(tempfile -m 666 -d "$WORKDIR")"
    DPEP_TAGLINENUM="$(grep -n '^@DPATCH@$' "$OLDPATCH" | head -n1 | cut -f1 -d:)"
    if [ "$DPEP_TAGLINENUM" ]; then
	# They have our tag, so we can preserve their headers.
	dpep_message norm "@DPATCH@ tag found, preserving dpatch header."
	head -n "$DPEP_TAGLINENUM" "$OLDPATCH" > "$NEWPATCH"
    elif [[ -e "debian/patches/00template" ]]; then
	# Okay, they don't have a tag - damn them. But they at least have a
	# template.
	dpep_message warn "@DPATCH@ tag not found, using debian/patches/00template"
	dpep_template_apply "$OLDPATCH" "$DPEP_DESC"
    else
	# They have neither a @DPATCH@ tag, *NOR* a template. Damn, they just suck.
	dpep_message warn "@DPATCH@ tag not found, debian/patches/00template not found. Using hardcoded default."
	dpep_template_hardcoded "$NEWPATCH" "$OLDPATCH" "$DPEP_DESC"
    fi
    # Okay, the headers and shell snippets are in place. Move the diff there now.
    cat "$DIFFHOLDER" >> "$NEWPATCH"
    mv "$NEWPATCH" "$OLDPATCH"
    dpep_message norm "$OLDPATCH updated."
fi
# chmod +x the dpatch, just in case.
chmod +x "$DPEP_OUTDIR/$DPEP_PATCH"

# Okay, we're all done. Do the cleanup.
dpep_cleanup

# arch-tag: ef9b2d2d-2026-4f10-b88d-330ea9039b14
