#!/bin/bash
# ------------------------------------------------------------------------------
# Copyright (c) 2016 SUSE Linux GmbH, Nuernberg, Germany.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of version 2 of the GNU General Public License as published by the
# Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, contact SUSE Linux GmbH.
#
# ------------------------------------------------------------------------------
# cs_man2pdf
# Convert man pages to PDF format.
# Version: 2016-02-02
# Author: L.Pinne

EXE="$0"
ERR="/dev/null"

function show_help(){
	echo "usage: $(basename $0) --help | --version"
	echo "usage: $(basename $0) --dir <dir>"
	echo "usage: $(basename $0) --rpm <rpm>"
	echo "usage: $(basename $0) <man_page> <section>"
	echo
	echo " --dir <dir>	convert man pages from directory."
	echo " --rpm <rpm>	convert man pages from installed RPM."
	echo " --help		show help."
	echo " --version	show version."
}


function from_dir(){
	# TODO common awk sub-function for all from_ functions
	R=$1
	ls "${1}"/ | while read; do echo $REPLY |\
	awk -F"." 'NF==3 && $3=="gz" {print $1,$2}
		   NF==4 && $4=="gz" {print $1"."$2,$3}
		   NF==3 && $3!="gz" {print $1"."$2,$3}'; done |\
	while read; do do_man2pdf $REPLY; done
}


function from_rpm(){
	R=$1
	rpm -ql $R | grep "/man/" | while read; do basename $REPLY; done |\
	awk -F"." 'NF==3 && $3=="gz" {print $1,$2}
		   NF==4 && $4=="gz" {print $1"."$2,$3}
		   NF==3 && $3!="gz" {print $1"."$2,$3}' |\
	while read; do do_man2pdf $REPLY; done
}


function do_man2pdf(){
	M=$1
	S=$2
	man -Tps $M $S 2>/dev/null | ps2pdf - >$M.$S.pdf 2>/dev/null
}


# main()

case $1 in
	-v|--version)
		echo -n "$(basename $EXE) "
		head -11 $EXE | grep "^# Version: "
		exit
	;;
	-h|--help)
		show_help
		exit
	;;
	-d|--dir)
		from_dir $2
		exit
	;;
	-r|--rpm)
		from_rpm $2
		exit
	;;
	*)
		# TODO better checks
		test $# -eq 2 || show_help
		do_man2pdf $1 $2
		exit
	;;
esac
#
