summaryrefslogblamecommitdiff
path: root/bin/vtoc.sh
blob: 11159d5d132b258603d5f0fdc1df9564e0c90a71 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13

         










                                                  






















                                                      




                                                                               








                                       




                                                                 

































                                                                              
                                                       





                    
#!/bin/sh

usage()
{
	cat <<- EOF
	Usage: ${0##*/} [options] [ contacts.vcf ]
	convert vcf file to csv file
	Options:
	  -h	show this help cruft

	EOF
}

die()
{
	: "${1:?}"

	printf "\033[31;1merr: %b\033[0m\n" "$1" 1>&2
	exit "${2:-1}"
}

warn()
{
	: "${1:?}"
	printf "\033[33;1mwarn: %b\033[0m\n" "$*" 1>&2
}

########
# MAIN #
# ######

name=
no=
vcf=
nos=

if [ -z "$1" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	usage
	exit
elif [ "$(file --brief --dereference --mime-type "$1")" != "text/vcard" ]; then
	die "input is not a vcf file"
else
	vcf="$1"
	shift
fi

strings "$vcf" | while read -r line; do
	case "$line" in
	'FN:'*)
		name="${line##*:}"
		case "$name" in
		*,*)
			name="$(printf "%s" "$name" | tr -d ',')"
			;;
		esac
		;;
	'TEL;TYPE='*':'*)
		# avoid repetitions in same vacrd entry
		no="${line##*:}"
		case "$nos" in
		*"$no"*)
			continue
			;;
		esac
		nos="${nos}:${no}"

		# make sure $no is E.164-formatted
		case "$no" in
		*-*)
			no="$(printf "%s" "$no" | tr -d '-')"
			;;
		esac
		case "$no" in
		+[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])
			# gotta go fast \+[0-9]{12}
			;;
		+974[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]) # qatar
			# gotta go fast \+974{8}
			;;
		*)
			warn "illegal format: ${name}, ${no}"
			continue;
			;;
		esac

		[ "$1" = "-w" ] &&
			continue

		[ -n "$no" ] &&
			printf "%s, %s\n" "$name" "$no"
		;;
	'END:VCARD')
		nos=
		;;
	esac
done