#! /bin/bash

##  toolbox for the Partclone
##  initial copied from VLC
##  Authors: thomas thomas at nchc dot org dot tw 

###
###  Get a sane environment, just in case
###
LC_ALL=C
export LC_ALL
LANG=C
export LANG

##
##  Give help
##
help()
{
  cat << EOF
recognized flags are:
  --update-po             update translation files
  --update-log            update Changelog files from git
  --update-contributors   update CONTRIBUTORS files from git
  --update-changelog      update debian/rpm packaging changelog entries
  --update-btrfs          update source of btrfs
    eg:
    ./toolbox --update-btrfs /tmp/partclone /tmp/btrfs-progs v6.8
EOF
  exit 1
}

##
## update btrfs
##

btrfs_update(){
    partcloneGitRepo=$1
    btrfsprogsGitRepo=$2
    tag=$3
    echo $@ $tag $partcloneGitRepo $btrfsprogsGitRepo

    pushd $partcloneGitRepo/src/
        btrfs_files=$(find btrfs -name "*.h" -o -name "*.c")
    popd
    echo $btrfs_files

    pushd $btrfsprogsGitRepo

        git checkout -b $tag $tag
        ./autogen.sh
        ./configure --disable-documentation 
        make

        cat libbtrfs/version.h

        set -e
        for source_file in $btrfs_files; do 
            echo $source_file
            btrfs_file=$(echo $source_file | sed s/^btrfs//)
            source_file_path=$(echo "$partcloneGitRepo/src/$source_file" | sed "s#//#/#g")
            btrfs_file_path=$(echo "$btrfsprogsGitRepo/$btrfs_file" | sed "s#//#/#g")

            if test -f "$btrfs_file_path"; then
                source_md5=$(md5sum -z $source_file_path |sed 's/ .*//')
                btrfs_md5=$(md5sum -z $btrfs_file_path |sed 's/ .*//')

                if [ "X$source_md5" != "X$btrfs_md5" ]; then
                    echo "cp $btrfs_file_path $source_file_path"
                    cp $btrfs_file_path $source_file_path
                else
                    echo "keep $source_file"
                fi
                echo "MD5: $source_md5 : $btrfs_md5"
            else
                echo "######"
                echo "can't find $source_file in $btrfs_file_path"
                echo "manually merge file!"
                find $btrfsprogsGitRepo -name `basename $source_file`
                echo "######"
            fi

        done

    popd
}

###
###  argument check
###

if test "$1" = ""
then
  help
fi

case "$1" in
  --update-po)
    action=po
    ;;
  --update-btrfs)
    action=btrfs
    ;;
  --update-contributors)
    action=contributors
    ;;
  --update-log)
    action=changelog
    ;;
  --update-changelog)
    action=packaging-changelog
    ;;
  --help)
    help
    ;;
  *)
    echo "$0: unknown option $1"
    help
    ;;
esac
shift

##
##  Update CONTRIBUTORS file
##
if test "${action}" = "contributors"
then
  git shortlog -sn > CONTRIBUTORS
  exit $?
fi

##
##  Update the potfiles because no one ever does it
##
if test "${action}" = "po"
then
  # find out the source files
  echo "WARNING: you should run \"make update-po\" instead!" >&2
  cd po
  make update-po
  exit $?
fi

##
##  Update the source of btrfs
##

if test "${action}" = "btrfs"
then
    echo "btrfs sync parameters $@"
    btrfs_update $@
fi

##
## update Changelog from SVN
##
#if test "${action}" = "changelog"
#then
#  echo "Would you want to export svn log to ChangeLog(y/N)?"
#  read log
#  case "$log" in  
#    [yY] | [Yy][Ee][Ss] )
#      if which svn2cl 2>&1 >/dev/null ; then
#        echo "please input svn password to export svn log."
#        svn2cl --reparagraph --break-before-msg=2
#      else
#        echo "WARNING: you should install subversion-tools firstly."
#      fi
#      ;;
#    esac
#  exit $?
#fi
#

if test "${action}" = "changelog"
then
    # get source code from Jim Meyering at 
    # http://git.mymadcat.com/index.php/p/tracker/source/tree/master/gitlog-to-changelog
    perl gitlog-to-changelog --since 1999-01-01 > ChangeLog
fi

##
##  Update debian/rpm packaging changelog entries for a release
##  (run before committing and tagging; idempotent)
##
if test "${action}" = "packaging-changelog"
then
    set -e
    if ! command -v dpkg-parsechangelog > /dev/null; then
        echo "dpkg-parsechangelog not found - install dpkg-dev" >&2
        exit 1
    fi
    VER=$(sed -n 's/^AC_INIT(\[Partclone\],\[\([^]]*\)\].*/\1/p' configure.ac)
    if test -z "$VER"; then
        echo "cannot read version from configure.ac AC_INIT" >&2
        exit 1
    fi
    echo "version from configure.ac: $VER"

    PREV_TAG=$(git tag --sort=-creatordate | grep -vFx "$VER" | head -1 || true)
    RANGE="${PREV_TAG:+$PREV_TAG..HEAD}"
    echo "bullets from: ${RANGE:-<no previous tag, last 30 commits>}"

    #
    # debian changelog: preprend "VER-1~gh1" entry unless already on top
    #
    DEBVER="${VER}-1~gh1"
    DEBCHLOG=README.Packages/debian.sid/changelog
    TOP=$(dpkg-parsechangelog -l "$DEBCHLOG" -S Version)
    if test "$TOP" = "$DEBVER"; then
        echo "$DEBCHLOG already at $DEBVER"
    else
        NEW_ENTRY=$(mktemp)
        CANDIDATE=$(mktemp)
        {
            echo "partclone (${DEBVER}) sid; urgency=medium"
            echo
            echo "  * Automated upstream release build ${VER}."
            git log --no-merges --format='%s (%h)' $RANGE | head -30 | sed 's/^/  * /'
            echo
            echo " -- Thomas Tsai <tlinux.tsai@gmail.com>  $(LC_ALL=C date -R)"
            echo
        } > "$NEW_ENTRY"
        cat "$NEW_ENTRY" "$DEBCHLOG" > "$CANDIDATE"
        rm -f "$NEW_ENTRY"
        if dpkg-parsechangelog -l "$CANDIDATE" -S Version | grep -qx "$DEBVER"; then
            mv "$CANDIDATE" "$DEBCHLOG"
            echo "updated $DEBCHLOG to $DEBVER"
        else
            echo "generated debian changelog entry is invalid; $DEBCHLOG left unchanged" >&2
            rm -f "$CANDIDATE"
            exit 1
        fi
    fi

    #
    # rpm spec: sync Version: and prepend a %changelog entry
    #
    SPEC=README.Packages/partclone.spec
    TOPV=$(sed -n 's/^Version:[[:space:]]*//p' "$SPEC" | head -1)
    if test "$TOPV" != "$VER"; then
        sed -i.bak "s/^Version:.*/Version:      ${VER}/" "$SPEC"
        rm -f "$SPEC.bak"
        echo "updated $SPEC Version to $VER"
    else
        echo "$SPEC Version already at $VER"
    fi
    if grep -A3 '^%changelog' "$SPEC" | grep -qF -- "- ${VER}-"; then
        echo "$SPEC %changelog already has an entry for $VER"
    else
        DATE=$(LC_ALL=C date '+%a %b %d %Y')
        ENTRY=$(mktemp)
        {
            echo "* ${DATE} Thomas Tsai <tlinux.tsai@gmail.com> - ${VER}-1.gh1"
            echo "- Automated upstream release build ${VER}."
            echo
        } > "$ENTRY"
        sed -i "/^%changelog$/r $ENTRY" "$SPEC"
        rm -f "$ENTRY"
        echo "added %changelog entry for $VER to $SPEC"
    fi

    echo
    echo "done. review with: git diff README.Packages/"
    exit 0
fi
