#!/bin/bash
set -e

# copyright David Bannon, 2019, 2020, 2021 use as you see fit, but retain this statement.
#
# This stript is useful to prepare the tomboy-ng source tree to make an
# Debian Source Package

# If you submit it to Debian Mentors and get an error, or a revision of the packaging
# is requested, DO NOT DELETE THE WORKING Build* DIR, you need it to generate 
# fixes (run prepare.debian again, this time without the -n. Totally different 
# behaviour !

# Fine to blow it away if its not been uploaded with dput ! 

# Possibly fine to blow it away if it has not migrated from Mentors to unstable.
# But that needs clarification.

# For detailed instructions including ready to copy command lines see-
# https://github.com/tomboy-notes/tomboy-ng/blob/master/prepare.md


# 
# David Bannon, Jan 2021
# History -
#	2020-09-02 Added -D distro switch
#       2020-12-17 Restructed the multi control system to make it clearer.
#       2020-12-29 Split script into seperate Debian one, only Qt5.
#       2021-01-27 More detailed instructions on use.
#	2021-02-03 Include enough of first changelog to keep lintian off my back
#	2021-06-19 Made swichable between GTK2 and Qt5
#		   Moved Howto docs to github
#   2022-11-17 Now two seperate behavious, with -n, "new release" we download a new
#              set of files and generate a new .orig.tar.gz that must be uploaded.
#              Secondly, without the -n, we assume we are using an existing .orig.
#              and just repackaging. The Package version number is manually incremented and
#              the src dir renamed. Most of the code is skipped.
#   2022-11-30 Don't try to imcrement pack numb, must be done manually.

APP="tomboy-ng"
# These are mine, they are used as defaults if NOT set in env. Ignored unless signing.
DEF_EMAIL="tomboy-ng@bannons.id.au"	# This matches cert I use to sign tomboy-ng stuff
DEF_FULLNAME="David Bannon"		# and this ...
UBUNTU_FULLNAME="tomboy-ng"		# My stuff up, different cert with different name in Ubuntu PPA !
DEBVER="-1"		# Package version, not source, starts at 1, is auto set if repackage mode, don't edit
NEWORIG="no"    # set to yes if -n on command line
DISTRO1="unstable"
TB_SOURCE="master" # might be, eg, 0.35 etc, valid github tag, set with command line

# Housekeeping stuff, helpers for debugging etc. Set with command line, not here !
VER="unknown"
LAZ_BLD=""
UFILES="NO"	# debug tool, update Makefile
CLEAN="NO"	# debug tool, remove files from previous run, assume same ver.
WIDGET=""	# empty says make a GTK2, only other possibility is Qt5
REPACK_REASON=""    # set with -r, few words about why repackaging necessary

	# Looks for fpc and lazbuild on PATH, if in root space, do nothing,
	# if in user space, because debuild will miss them, makes two files.
function CheckFPC_LAZ () {
	FPC=`which fpc`
	if [ -x "$FPC" ]; then
		PREFIX="${FPC:0:4}"
		if [ "$PREFIX" = "/usr" ]; then
			echo "---------- root space fpc, all good"
		else
			echo "---------- Leaving a fpc file for buildit"
			echo "$FPC" > WHICHFPC
		fi
	else
		echo "----------- ERROR, no fpc found ------------"
		exit 1
	fi
	if [ "$LAZ_BLD" = "" ]; then 	# we had better try to find it		
		LAZ_BLD=`which lazbuild`
	fi
	if [ -x "$LAZ_BLD" ]; then
		PREFIX="${LAZ_BLD:0:4}"
		if [ "$PREFIX" = "/usr" ]; then
			echo "---------- root space Lazarus, all good"
		else
			echo "---------- Leaving a lazbuild file for buildit"
			echo "$LAZ_BLD" > WHICHLAZ
		fi
	else
		echo " --- ERROR, no lazbuild found, try -l ? ---"
		exit 1
	fi
}               # End of function

	# Here we remove file that are not needed in the Debian SRC kit.
function CleanSource () {
	rm -Rf experimental
	rm -Rf patches
	rm -Rf doc/gallery
	rm -Rf doc/html
	rm -Rf doc/wiki
	rm -Rf po/*.mo
	rm -f  doc/*.svg doc/*.png doc/*.note
	rm -f  glyphs/*.png glyphs/*.ico glyphs/*.svg glyphs/*.icns
	rm -fR glyphs/help
	rm -fR glyphs/demos
	KC="kcontrols"
	KCS="$KC/source"
	rm -fR "$KC"/demos 
	rm -fR "$KC"/help
	rm -Rf "$KC"/packages kcontrols/tools 
	rm -Rf "$KC"/resource_src/khexeditor_icons "$KC"/resource_src/kgrid_icons
	rm "$KCS"/kbuttons.pas "$KCS"/kdbgrids.pas "$KCS"/kgrids.* "$KCS"/kicon.pas 
	rm "$KCS"/klabels.pas "$KCS"/kmemodlg*.* "$KCS"/kxml.pas "$KCS"/kwidewinprocs.pas
	rm "$KCS"/kmemofrm.* "$KCS"/kpagecontrol.* "$KCS"/kprogress.* "$KCS"/ksplitter.pas  
	rm "$KC"/*.txt "$KC"/*.json "$KC"/*.bat
	rm -Rf "$KC"/packages "$KC"/tools "$KC"/resource_src/khexeditor_icons "$KC"/resource_src/kgrid_icons
	chmod 664 doc/HELP/EN/*
	chmod 664 doc/HELP/ES/*
	chmod 664 doc/HELP/FR/*

}         # End of function  


function KControls () {	
	if [ -e "kcontrols-master.zip" ]; then
		echo "---------- Note: reusing KControls zip"
	else
		wget https://github.com/davidbannon/KControls/archive/master.zip   # watch this name does not change.
		mv master.zip kcontrols-master.zip
	fi
	unzip -q kcontrols-master.zip
	# rm -f master.zip
	mv KControls-master "$APP"_"$VER""$DEBVER"/kcontrols
}               # End of function

function ShowHelp () {
    echo " "
    echo "Prepares a tomboy-ng source to build (ie Debian SRC Package or local make)"
    echo "Assumes FPC of some sort in path, available and working, >= 3.2.2."
    echo "Needs Lazarus, >= 3.2 in root space or specified with -l option."
    echo "For Debian packaging, needs devscripts preinstalled email and certs"
    echo "If doing a tomboy-ng release, provide -n and a new orig file is made."
    echo "(Else, repackaging - see the Repackaging section in prepare.md)"
    echo "Will download kcontrols, cleanup and prepare to run debuild -S"
    echo "REMEMBER to feed changlog back to github tree"
    echo "David Bannon, Aug 2024" 
    echo "-h   print this help message"
    echo "-l   a full path to lazbuild (inc 'lazbuild'), as part of a Lazarus install."
    echo "-C   clean ALL output files from previous run, REMOVES .orig file !"
    echo "-t   tomboy-ng source, defaults to master or github tag, eg, 0.35 etc"
    echo "-D   distro, defaults to unstable"
    echo "-n   New orig file, required for fresh release"
    echo "-r   Reason for repackage, use inverted commas, only if not -n"
    echo "-q   Make a Qt5 version instead of GTK2, ignored in repackage mode."
    echo "-p   Pause before creating Orig, make changes in annother terminal."
    echo ""
    echo "  Typically, new release     bash ./prepare.debian -n -q"
    exit
}          # End of function

function MakeOrigFile () {
    echo "---------- Creating a new .orig file"
    	# Note, when called we are in the unzipped and renamed tomboy-ng dir.
        # We move most of the debian dir out of harms way and tar up the dir.
    cd ..
    mv "$APP"_"$VER""$DEBVER"/debian ./debian
    mkdir "$APP"_"$VER""$DEBVER"/debian
    cp debian/copyright "$APP"_"$VER""$DEBVER"/debian/.
    tar czf "$APP"_"$VER".orig.tar.gz "$APP"_"$VER""$DEBVER"
	# OK, we now have our .orig. file, put most of it back.
    rm -Rf "$APP"_"$VER""$DEBVER"/debian
    mv ./debian "$APP"_"$VER""$DEBVER"/. 
}            # End of function


function PrepExistingOrigFile {
# Assume we are in a previously used dir, it will have orig and eg tomboy-ng_0.35-1 dir.
# Read the Repackaging section of prepare.md 
# you achive a similar position by extracting out .orig. with dpkg-source -x ....
# tomboy-ng_0.35.orig.tar.gz

NEWDIRNAME=`find . -maxdepth 1 -type d -name "tomboy*" `  # there should be only one and it must include a new packaging number
VER=`cat "$NEWDIRNAME"/package/version`

if [ -f "tomboy-ng_""$VER"".orig.tar.gz" ]; then
    echo "Orig file present, thats good"
else
    echo "Orig file not present, ""tomboy-ng_""$VER"".orig.tar.gz"
    echo "Giving up and going home ....."
fi

if [ -d "tomboy-ng-""$VER" ]; then
	echo "tomboy-ng_""$VER"" exists, you have not added a packaging number, EXITING"
	exit
fi

PACKVER=`echo "$NEWDIRNAME" | rev | cut -b 1 | rev `      # This is last char, wrong if user has not rev'ed

#NEWDIRNAME=`echo "$EXDIRNAME" | rev | cut -c2- | rev `   # chop off last char
#PACKVER=`echo "$EXDIRNAME" | rev | cut -b 1 | rev `      # This is last char
#((PACKVER=PACKVER+1))                                    # rev it, should test its not > 9
#NEWDIRNAME="$NEWDIRNAME""$PACKVER"
#mv $EXDIRNAME $NEWDIRNAME

rm -Rf *.dsc *.buildinfo *.changes *.debian.tar.xz
if [ "$DEBEMAIL" = "" ]; then
	DEBEMAIL="$DEF_EMAIL"
	export DEBEMAIL
fi
if [ "$DEBFULLNAME" = "" ]; then
	DEBFULLNAME="$DEF_FULLNAME"
	export DEBFULLNAME
fi
VER="$VER""-""$PACKVER"                                 # eg 0.35-2
cd "$NEWDIRNAME"
pwd
dch -v "$VER" -D"$DISTRO1" "$DISTRO2" "Repackage" 
if [ -n "$REPACK_REASON" ]; then
	dch --append "$REPACK_REASON"
fi   
cd ..
pwd 
echo "If no errrors, you should now cd $NEWDIRNAME"
echo "Make what ever changes seem appropriate and run  debuild -S; cd .."
exit                                                    # My work here is done
}       # End of function


while getopts "hUCl:D:nqQt:r:p" opt; do
  case $opt in
    h)
      ShowHelp
      ;;
    l)
	LAZ_BLD="$OPTARG"
	;;
    C)
	# CLEAN="YES"
	rm -Rf "$APP""_"*		# note the underscore !
	exit
	;;
    D)
    DISTRO1="$OPTARG"
	# DISTRO1="-D""$OPTARG"
	DISTRO2="--force-distribution"
	;;
	n)
	NEWORIG="YES"
	;;
	r)
	REPACK_REASON="$OPTARG"
	;;
	t)
	TB_SOURCE="$OPTARG"
	;;
	Q)
	WIDGET="Qt5"
	;;
    q)
	WIDGET="Qt5"
	;;
    p)
	PAUSE="YES"
        ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ShowHelp
      ;;
  esac
done

ORIGFILE=`find . -maxdepth 1 -name "*.orig.tar.gz" `
echo "orig file is $ORIGFILE and NEWORIG is ""$NEWORIG"
if [ "$NEWORIG" == "no" ]; then              # if no -n, we always exit here.
    if [ "$ORIGFILE" == "" ]; then
        echo "Sorry, this directory does not contain a .orig.tar.gz file and we"
        echo "cannot work in repackage mode without one, if a new release, -n ?"
	exit
    else
        PrepExistingOrigFile       
    fi
    exit
fi

if [ "$ORIGFILE" == "" ]; then
    echo "No orig.tar.gz file found, confirming New Build"
else
    echo "An orig.tar.gz was found, you might need it to revise submitted packaging, drop"
    echo "the -n. Otherwise blow old files away and start a New Release"
    exit
fi   

echo "---------- laz_bld is $LAZ_BLD"
echo "---------- CLEAN   is $CLEAN"
echo "---------- UFILES  is $UFILES"
echo "---------- Target  is $DISTRO1"
echo "---------- WIDGET  is $WIDGET"
echo "---------- NEWORIG is $NEWORIG"
echo "---------- DebVer  is $DebVer"


rm -f WHICHFPC WHICHLAZ		# remove any existing semaphore files

if [ ! -f tomboy-ng-master.zip ]; then		# We need download TB source
	echo "---------- Downloading a new tomboy-ng, $TB_SOURCE"
	if [ "$TB_SOURCE" == "master" ]; then
		wget https://github.com/tomboy-notes/tomboy-ng/archive/master.zip
		mv master.zip tomboy-ng-master.zip
	else
		# note, github plays with the file name ???? Some pressure to be consistent with tag names !
		wget https://github.com/tomboy-notes/tomboy-ng/archive/refs/tags/v"$TB_SOURCE".zip
		mv tomboy-ng-"$TB_SOURCE".zip tomboy-ng-master.zip
		# we download https://github.com/tomboy-notes/tomboy-ng/archive/refs/tags/v0.35.zip
		# but end up with tomboy-ng-0.35.zip, note the 'v' disappeared, gee !
	fi
else
	echo "Reusing existing tomboy-ng zip"
fi

# https://github.com/tomboy-notes/tomboy-ng/archive/refs/tags/v0.35.zip


if [ -f tomboy-ng-master.zip ]; then
	CheckFPC_LAZ
	# In practise, we should have these env set, my defaults just in case. 
	if [ "$DEBEMAIL" = "" ]; then
		DEBEMAIL="$DEF_EMAIL"
		export DEBEMAIL
	fi
	if [ "$DEBFULLNAME" = "" ]; then
		DEBFULLNAME="$DEF_FULLNAME"
		export DEBFULLNAME
	fi
	if [ "$CLEAN" = "YES" ]; then
		rm -Rf "tomboy-ng-master"		# probably not here anyway ....
	fi
	unzip -q tomboy-ng-master.zip

	# But, if we are trying to make an old version and renamed the TB source then
	# the new dir created above might be called something like tomboy-ng-0.34
	if [ ! -e "tomboy-ng-master" ]; then
		EXDIRNAME=`find . -maxdepth 1 -type d -name "tomboy-ng-0*" `  # there should be only one, I hope ...
		echo " --------- mv $EXDIRNAME tomboy-ng-master"
		mv "$EXDIRNAME" "tomboy-ng-master"
	fi

	# risky, hacky code follows, versions 0.34 and earlier did not have mkcontrol.bash, slip one in
	if [ -e "mkcontrol.bash" ]; then
		echo "-------- WARNING, using local mkcontrol.bash because its here !"
		cp mkcontrol.bash tomboy-ng-master/scripts/.
		cp control.template tomboy-ng-master/debian/.
	fi
	VER=`cat tomboy-ng-master/package/version`
	mv "tomboy-ng-master" "$APP"_"$VER""$DEBVER"
	KControls
	
	#echo -----------------------------------------------------------------------
	#echo     Disabling use of UseAppIndVar because probably still using Laz226
	#echo -----------------------------------------------------------------------
	#sed -i "s/define APPINDPATCH/ignore/" "$APP"_"$VER""$DEBVER"/source/Tomboy_NG.lpr
	# Remove the above line when Debian moves to Laz300
	
	cd "$APP"_"$VER""$DEBVER"	# This is orig tomboy-ng dir made from zip
	if [ "$WIDGET" = "Qt5" ]; then
	    touch Qt5			# leave semaphore file
	    scripts/mkcontrol.bash debian/ "$DISTRO1" qt5
	    # we must force qt5 app to use qt5ct because of a bug in qt5.tsavedialog
	    #sed -i "s/Exec=tomboy-ng %f/Exec=env QT_QPA_PLATFORMTHEME=qt5ct tomboy-ng %f/" "glyphs"/"$APP".desktop
	    # sed -i "s/Exec=tomboy-ng %f/Exec=QT_QPA_PLATFORMTHEME=qt5ct tomboy-ng %f/" "glyphs"/"$APP".desktop
	    # NO, we don't. Bug is not present in L226 or L300, only intermediate ones.
	else
		scripts/mkcontrol.bash debian/ "$DISTRO1"
	fi

        if [ "$PAUSE" = "YES" ]; then
		read -p "Edit things in another terminal, press Enter here."
	fi


    # Note : if not NEWORIG, we cannot possibly be here !
	if [ "$NEWORIG" = "YES" ]; then
	    CleanSource
		date +\'%Y/%m/%d\' > source/SOURCE_DATE      # thats to provide a reproducable date

		MakeOrigFile                    # create new .orig (and no longer a new change log)
	fi

	cd "$APP"_"$VER""$DEBVER"

	dch -v "$VER""$DEBVER" -D"$DISTRO1" "$DISTRO2" "Release of new version."    
	if [ -f whatsnew ]; then
	    echo "---------- Including whatsnew in changelog"
	    while IFS= read -r Line; do
		dch --append "$Line"
	    done < whatsnew
	fi
	dch --append "Please see github for further change details."

	#cp debian/control.debian debian/control			# thats the GTK2 version
	#if [ "$WIDGET" = "Qt5" ]; then
	#	cp debian/control.qt5-DEBIAN debian/control	# thats the Qt5 version
	#fi
	rm -f debian/control.qt5
	rm -f debian/rules.qt5		# never need that here, its for PPA where qt5 has different name
	rm -f debian/control.qt5-DEBIAN
	rm -f debian/control.debian		
	cd ..
	echo "If no errrors, you should now cd ""$APP"_"$VER""$DEBVER""; debuild -S; cd .."
else
	echo ""
	echo "   Sorry, I cannot see a tomboy-ng-master.zip file. This"
	echo "   script must be run in a directory containing that file"
	echo "   obtained from github and probably little else."
	echo "   If you used wget to download tomboy-ng, it will be named master.zip,"
	echo "   you should rename it tomboy-ng-master.zip to avoid confusion."
	echo "-"
fi



