#!/bin/bash

modulename='Net::LDAP::SimpleServer'
modulepath=$(echo $modulename | sed -e 's/::/\//g').pm
moduledash=$(echo $modulename | sed -e 's/::/-/g')

dry_run=1
[ "$1" = "-f" ] && dry_run=0

is_dry_run() {
  [[ "${dry_run}" -eq 1 ]]
}

msg() {
  echo "$@" >&2
}

msg "== Checking current directory"
[ -f ./MANIFEST ] || {
    msg "**** Cannot find ./MANIFEST"
    exit 1
}
[ -f ./lib/${modulepath} ] || {
    msg "**** Cannot find ./lib/${modulepath}"
    exit 1
}

is_dry_run && {
    msg "***** DRY-RUN: use -f to actually commit! *****"
}

_tidy() {
    dir="$1"; shift
    spec="$1"; shift

    eval "find $dir -name '$spec' | xargs perltidy -b"
}

msg "== Running through perltidy"
{ _tidy lib/ '*.pm' && _tidy t/ '*.t' && _tidy ./ '*.[Pp][Ll]'; } || {
    msg "**** Failed syntax check! Aborting."
    exit 1
}

msg "== Sorting contents of MANIFEST"
{ sort MANIFEST > __manifest && mv __manifest MANIFEST; } || {
    msg "**** Cannot sort the MANIFEST file. Aborting."
    exit 1
}

msg "== Running ./Build.PL"
perl ./Build.PL || exit 1

msg "== Running tests"
./Build disttest || exit 1

version=$(perl -nle 'if( /^version/ ) { s/^\S+\s+v//; print; }' META.yml)
msg "== Version: ${version}"

msg "== Adding module to git"
is_dry_run || { git add lib/${modulepath} || exit 1; }

msg "== Making README"
( cd lib; perldoc -t -F ${modulepath} > ../__readme ) || exit 1
is_dry_run || { cp __readme README && git add README || exit 1; }

msg "== Checking <Changes> file for this version"
grep -q "^${version}" Changes && {
  msg "**** VERSION ${version} is already in Changes. Aborting..."
  exit 1
}

msg "== Generating <Changes> automagically"
{
    echo "Revision history for ${moduledash}"
    echo ""
    printf '%-7s [%s] %s\n' "${version}" "$(date '+%Y.%m.%d %H:%M:%S')" \
        "${modulename} DIST VERSION ${version}"
    perl -e 'print "="x7 . " " . "="x70 . "\n"'
    git log --oneline | perl -nle 'exit if /DIST VERSION/; print "$_";' &&
    echo "" &&
    cat Changes | perl -e '$a=<>; $a=<>; while(<>) { print }'
} | tee __changes | head -20 || exit 1
is_dry_run || { cp __changes Changes && git add Changes || exit 1; }

msg "== Committing files to git"
is_dry_run || { git commit -m "DIST VERSION ${version}" || exit 1; }

msg "== Tagging as v${version}"
is_dry_run || { git tag v${version} HEAD || exit 1; }

msg "== Making distribution package"
./Build dist || exit 1

d=$(echo ${moduledash}*.tar.gz) 
msg "== Moving file $d to home directory"
is_dry_run || mv $d ${HOME}

msg "== Cleaning directory"
is_dry_run || git clean -fd

is_dry_run && { msg "***** DRY-RUN: use -f to actually commit! *****"; }

