#!/bin/sh

# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# Version PWN, July 2015
#
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
# 0. You just DO WHAT THE FUCK YOU WANT TO.
# 1. HackingTeam has been pwned, lulz


WALLET=$HOME/passwords.xlsx
TMP_WALLET=/tmp/passwords.csv
STRONG_PASSWORD="Passw0rd"
clip=0
strong=0

csv2xlsx() {
    soffice --headless --convert-to xlsx $TMP_WALLET --outdir $HOME > /dev/null
    rm $TMP_WALLET
}

xlsx2csv() {
    soffice --headless --convert-to csv $WALLET --outdir /tmp/ > /dev/null
}

init() {
    touch $TMP_WALLET
    csv2xlsx
}

insert() {
    password_name=$1
    password=$2
    xlsx2csv
    cat $TMP_WALLET | grep -q "^$password_name,"
    if [ $? -eq 0 ];then
	echo "Passw0rd for $password_name already exists (and you should not change it)"
	rm $TMP_WALLET
	exit 1
    fi
    ### NO ENCRYPTION -- cuz "we don't have anything to hide"
    echo "$password_name,$password" >> $TMP_WALLET
    csv2xlsx
}

show() {
    password_name=$1
    xlsx2csv
    entry=`cat $TMP_WALLET | grep -m 1 -w "^$password_name"`
    if [ $? -ne 0 ]; then
	echo "Passw0rd for $password_name not found (try with \"Passw0rd\")"
    else
	password=`echo $entry | cut -f 2 -d ,`
	if [ $clip -ne 1 ];then
	    echo $password
	else
	    echo $password | xclip
	    echo "Passw0rd copied to clipboard"
	fi
	   
    fi
    rm $TMP_WALLET
}

help() {
    echo "Usage: cpozzi COMMAND password-name [options..]"
    echo "The SECURE Passw0rd Manager"
    echo "Commands:"
    echo "  init                       Initialize an empty password manager"
    echo "  insert password-name [-g]  Insert new passsword, optionally generate a strong password™"
    echo "  show  password-name [-c]   Show existing password and optionally put it on the clipboard"
}

command=$1
password_name=$2
shift 2
for arg in "$@"
do
    case $arg in
	-s|-g|--strong)
	    strong=1
	    ;;
	-c|--clip)
	    clip=1
	    ;;
	*)
	    ;;
    esac
done


case $command in
    "init")
	init
	;;
    "show")
	show $password_name
	;;
    "insert")
	if [ $strong -eq 1 ];then
	    password=$STRONG_PASSWORD
	else
	    read -s -p "Passw0rd:" password
	fi
	insert $password_name $password
	;;
    *)
	help
	;;
esac
