-#!/bin/zsh
+#!/bin/sh
-# Copyright 2014 Paul Hänsch
+# Copyright 2014, 2019 Paul Hänsch
#
# This file is part of Confetti.
#
# You should have received a copy of the GNU Affero General Public License
# along with Confetti. If not, see <http://www.gnu.org/licenses/>.
-cgi_post
-cgi_refdata
+filter="$(REF f)"
+order="$(REF o)"
-filter="&filter=${_REF[filter]}"
-filtertype="&filtertype=${_REF[filtertype]}"
-order="&order=${_REF[order]}"
-
-uid=$(uuidgenerator)
+uid="$(timeid)$(randomid)" # 32 Octets UID, starting with timestamp
card="${uid}.vcf"
-tempfile="$_DATA/temp/$card"
-
-cat >"$tempfile" <<EOF
-BEGIN:VCARD
-VERSION:4.0
-N:;;;;
-BDAY:
-TEL:
-EMAIL:
-ADR:
-NOTE:
-UID:$uid
-END:VCARD
-EOF
-
-echo -n "Location: ?p=cards${filter}${filtertype}${order}&edit=$card\n\n"
+vcf_escape(){
+ for each in "$@"; do
+ printf %s\\n "$each" \
+ | sed -E ':X;$!{N;bX}; s;\r\n;\n;g; s;([;,\\]);\\\1;g; s;\n;\\n;g;'
+ done \
+ | sed -E ':X;$!{N;bX}; s;\n;\;;g'
+}
+
+IFS='|' read -r date fn ln bday bmonth byear tel tcell junk1 email junk2 note <<-EOF
+ $(POST seed |tr \\t \|)
+ EOF
+
+[ ${#byear} = 1 ] && byear="200$byear"
+[ ${#byear} = 2 ] && byear="20$byear"
+[ ${#bmonth} = 1 ] && bmonth="0$bmonth"
+[ ${#bday} = 1 ] && bday="0$bday"
+
+mn=""
+case $fn in
+ *\ *)
+ mn="${fn#* }"
+ fn="${fn%% *}"
+ ;;
+esac
+
+mkdir -p "${_DATA}/lock/vcard/"
+lockdir="${_DATA}/lock/vcard/${card}/"
+lockfile=${lockdir}/${SESSION_ID}
+
+if mkdir "$lockdir"; then
+ cat >"$lockfile" <<-EOF
+ BEGIN:VCARD
+ VERSION:4.0
+ N:$(vcf_escape "$ln" "$fn" "$mn" "" "")
+ FN:$(vcf_escape "${fn}${mn:+ }${mn} ${ln}")
+ BDAY:$(parse_date "${byear}-${bmonth}-${bday}")
+ TEL:$(vcf_escape "$tel")
+ TEL;TYPE=CELL:$(vcf_escape "$tcell")
+ EMAIL:$(vcf_escape "$email")
+ X-ZACK-JOINDATE:$(parse_date "$date")
+ ADR:
+ NOTE:$(vcf_escape "$note")
+ UID:${uid}
+ END:VCARD
+ EOF
+ REDIRECT "${_BASE}/cards/?o=${order}&f=${filter}&e=${card}"
+else
+ SET_COOKIE session message="EDITLOCK"
+ REDIRECT "${_BASE}/cards/?o=${order}&f=${filter}"
+fi