summaryrefslogtreecommitdiff
path: root/bin/ctov.sh
blob: 018b70ca4954c822f2c72fdf7a2fd4b09a953bd0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/bin/sh

vfmt="BEGIN:VCARD\r\n\
VERSION:3.0\r\n\
N:%s;;;;\r\n\
FN:%s\r\n\
TEL;TYPE=CELL:%s\r\n\
END:VCARD\r\n"

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

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

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

	EOF
}

trimstr()
{
	# usage trimstr <string>
	: "${1:?}"

	_str="${1%"${1##*[![:space:]]}"}"
	_str="${_str#"${_str%%[![:space:]]*}"}"

	printf "%s" "$_str"
	unset _str
}

makev()
{
	# usage makev <name> <no>
	: "${1:?}"
	: "${2:?}"
	# shellcheck disable=SC2059
	printf "$vfmt" "$1" "$1" "$2"
}

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

file=

while getopts "hf:" f; do
	case "$f" in
	f)
		file="$OPTARG"
		;;
	h)
		usage
		exit
		;;
	*)
		usage
		exit 1
	esac
done

if [ -n "$file" ] &&
 [ "$(file --brief --dereference --mime-type "$file")" != "application/csv" ]; then
	die "input is not a csv file"
fi

while read -r entry; do
	name=$(trimstr "${entry%%,*}")
	no=$(trimstr "${entry#*,}")

	makev "$name" "$no"
done <"${file:-/dev/stdin}"