summaryrefslogblamecommitdiff
path: root/bin/vtoc.sh
blob: fc691224c1b5bad8fd3874a3849bd574ddabb12f (plain) (tree)
























                                                      

                                                                           









                                       




                                                                 

































                                                                              
                                                       





                    
#!/bin/sh

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" ] ||
 [ "$(file --brief --dereference --mime-type "$1")" != "text/vcard" ]; then
	die "no or invalid input"
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" "$no" "$name"
		;;
	'END:VCARD')
		nos=
		;;
	esac
done