#!/bin/bash
#                       /usr/local/bin/addressbook_export
# https://crystalfaeries.net/posix/bin/addressbook_export
# celeste:crystalfaery ADDRESSBOOK_EXPORT 2021-04-19 03:45:53+00:00
# Export the abook addressbook to a multitude of formats
# NOTE: for some reason this has been aborting if and when
#	launched as a subtask rather than at the CLI...

cd	# there's no place like Om
	# NOTE: abook will error rather than overwrite target file, therefore, move old version out of the way
	mv			 "${HOME}"/.mutt/aliases					  "${HOME}"/.mutt/aliases- #backup
	abook --convert --infile "${HOME}"/.abook/addressbook --outformat mutt		--outfile "${HOME}"/.mutt/aliases

for type in allcsv bsdcal csv html ldif text vcard
do
	# NOTE: abook will error rather than overwrite target file, therefore, move old version out of the way
	mv			 "${HOME}"/.abook/abook."${type}"				  "${HOME}"/.abook/abook."${type}"- #backup
	abook --convert --infile "${HOME}"/.abook/addressbook --outformat "${type}"	--outfile "${HOME}"/.abook/abook."${type}"
done

# integrate the just-exported "${HOME}"/.abook/abook.bsdcal into 	"${HOME}"/.calendar/calendar
cat		"${HOME}"/.abook/abook.bsdcal		\
		"${HOME}"/.calendar/calendar		>	"${HOME}"/.calendar/calendar-
grep -i 'LANG='	"${HOME}"/.calendar/calendar-		>	"${HOME}"/.calendar/calendar
echo ''	>>	"${HOME}"/.calendar/calendar		#	Blank Line
sort -n <	"${HOME}"/.calendar/calendar-	|	\
uniq						|	\
grep -vi 'LANG='					>>	"${HOME}"/.calendar/calendar

# now break the single vcard file into individual vcards:
#(because my stupid flip-phone requires it be so)
rm -rf		~/.abook/vcf-	# toss the old backup
mv		~/.abook/vcf	~/.abook/vcf-
mkdir		~/.abook/vcf	# save recent backup
cd		~/.abook/vcf	# create new vcards
vcardbreak	~/.abook/abook.vcard	# from abook
for f in *.vcf
do
	$(echo -n "mv $f "; echo "`grep '^FN:' $f|sed 's/^FN://;s/ /_/g;s/$/\.vcf/'`")
done
name_tidy 

# now convert the ALL CSV file to GNU RecUtils format:
cd	"${HOME}"/.abook/		# return to the abook directory
mv	"${HOME}"/.abook/abook.rec	"${HOME}"/.abook/abook.rec-	#backup
# we need to un-comment the first line for csv2rec
sed -i 's/^#//'	abook.allcsv
csv2rec		abook.allcsv > abook.rec

