#!/bin/bash

if [ "q$1" == "q" ]; then
	echo "Usage: $0 [--list | --test] data.1pif [skipNum [amount]]"
	exit 1
fi
onlyList=0
if [ "$1" == "--list" ]; then
	echo "only listing"
	onlyList=1
	shift
fi
onlyTest=0
if [ "$1" == "--test" ]; then
	echo "only testing"
	onlyTest=1
	shift
fi

jsonOpts="-json_opt pretty,utf8,allow_bignum"
function getField {
	echo -e "$1\n" | json_pp $jsonOpts | grep "\"$2\" :" | tr -d ' ",' | head -n 1 | cut -f 2- -d: 
}

function getLastField {
	echo -e "$1\n" | json_pp $jsonOpts | grep "\"$2\" :" | tr -d ' ",' | tail -n 1 | cut -f 2- -d: 

}

skip=0

if [ "q$2" != "q" ]; then
	skip=$2
fi

amount=0
if [ "q$3" != "q" ]; then
	amount=$3
fi
trap ctrlc INT

function ctrlc(){
	echo "Exiting..." >&2
	exit 0
}

count=$(grep "**" $1 | wc -l|tr -d " \t")
echo "Found $count entries" >&2
if [ $skip -gt 0 ]; then
	echo "Skipping to $skip" >&2
fi
c=0
am=0;
while IFS= read -r line; do 
	let c=c+1
	if [ $c -lt $skip ]; then
		continue
	fi
	if [ $amount -gt 0 ] && [ $am -ge $amount ]; then
		echo "amount $amount reached" >&2
		exit 0
	fi	
	let am=am+1
	if echo "$line" | egrep '^\*\*' >/dev/null; then 
		echo "id" >/dev/null
	else 	
		echo "processing $c/$count" >&2
		line=$(echo "$line" | tr "\n\t\\" " " | sed -e 's/" "//g' )
		problematicPassword=""
		echo $line | json_pp $jsonOpts >/dev/null 2>&1|| {
			echo "Json error: $line"
			if echo "$line" | grep -i password >/dev/null; then
				problematicPassword=$(echo "$line" | sed -e 's/.*"password":"\([^}]*\).*/\1/')
				if echo "$problematicPassword" | grep "uuid" >/dev/null; then
					echo "Webform/Value?"
					problematicPassword=$(echo "$line" | sed -e 's/^.*\({.*"designation":"password"[^}]*}\).*$/\1/' | sed -e 's/.*"value":"\([^,}]*\)".*/\1/')
					username=$(echo "$line" | sed -e 's/^.*\({.*"designation":"username"[^}]*}\).*$/\1/' | sed -e 's/.*"value":"\([^,}]*\)".*/\1/')
					line=$(echo "$line" | sed -e 's/"title":""//g' | sed -e 's/"title":"Kunde"//g' | sed -e 's/"title":"Auftrag"//g' | sed -e 's/"title":"Herausgeber"//g')	
					title=$(echo "$line" | perl -pe 's/.*"title":"([^"]+).*$/\1/')
					path="passwords/$title"
					content="$password\nusername: $username"
					
				else 
					line=$(echo $line | sed -e 's/"password":"[^}]*"/"password":"$problematicPassword"/g')
				fi
				echo "got probably broken password: $problematicPassword"
				pp=$(echo "$problematicPassword" | sed -e 's/\([\\|\\"/]\)/\\\1/g')
				echo "Escaped $pp"
			elif echo "$line" | grep "wallet.computer.License" >/dev/null; then
				problematicPassword=$(echo "$line" | sed -e 's/.*"reg_code":"\([^},]*\).*/\1/')
				line=$(echo "$line" | sed -e 's/"title":""//g' | sed -e 's/"title":"Kunde"//g' | sed -e 's/"title":"Auftrag"//g' | sed -e 's/"title":"Herausgeber"//g')	
				title=$(echo "$line" | perl -pe 's/.*"title":"([^"]+).*$/\1/')
				regName=$(echo "$line" | perl -pe 's/.*"reg_name":"([^"]+).*$/\1/')
				regEmail=$(echo "$line" | perl -pe 's/.*"reg_email":"([^"]+).*$/\1/')
				echo "Problematic license...$problematicPassword"
				echo "Escaping license for '$title'"
				regCode=$(echo "$problematicPassword" | sed -e 's/\([\\|\\"/]\)/\\\1/g')
				path="licenses/$title"
				ccontent="$regCode\nRegisteredEmail: $regEmail\nRegisteredName: $regName";
			fi
			if [ "q$content" == "q" ]; then
				echo "resuming normal operation" >&2
			else 
				if [ $onlyList -ne 1 ]; then
					if [ $onlyTest -eq 1 ]; then
						echo -e "would insert to $path:\n$content"
					else 
						echo -e "$content" | pass insert -m -f "$path"
					fi
				fi
			fi
			continue

		}
		if [ $onlyList == 1 ]; then
			echo -e "$line\n" | json_pp $jsonOpts | while IFS= read l; do
			echo "$l" | sed -e "s/\$problematicPassword/$pp/g"
			done
		else
			#echo -e "$line\n" | json_pp $jsonOpts | grep typeName || ( echo "$line\n"; continue; )
			#type=$(echo -e "$line\n" | json_pp $jsonOpts | grep typeName | tr -d ' ",' | cut -f 2 -d:)
			type=$(getField "$line" "typeName")
			echo ">>>>>>>>> ====== Type: $type ======= <<<<<<<<<<<<"
			path=""
			content=""
			if [ "$type" == "system.folder.SavedSearch" ]; then
				echo -e "ignoring saved search"
			elif [ "$type" == "passwords.Password" ]; then
				location=$(getField "$line" "location" | tr -d ' ' ) 
				locationKey=$(getField "$line" "locationKey")
				title=$(getLastField "$line" "title")
				password=$(getField "$line" "password"| sed -e "s/\$problematicPassword/$pp/g")
				echo "Location >>> $location <<<"
				path="passwords/$title"
				content="$password\nLocation: $location"
			elif [ "$type" == "webforms.WebForm" ]; then
				url=$(getField "$line" "url")
				title=$(getLastField "$line" "title")
				password=$(echo -e "$line\n" | json_pp $jsonOpts | grep -A4 '"designation" : "password"' | grep '"value"' | cut -f2 -d: | tr -d '" '| sed -e "s/\$problematicPassword/$pp/g")
				username=$(echo -e "$line\n" | json_pp $jsonOpts | grep -A4 '"designation" : "username"' | grep '"value"' | cut -f2 -d: | tr -d '" ')
				path="passwords/$title"
				content="$password\nusername: $username"
			elif [ "$type" == "wallet.financial.CreditCard" ]; then
				bank=$(getField "$line" "bank")
				cardholder=$(getField "$line" "cardholder")
				ccnum=$(getField "$line" "ccnum")
				expirymm=$(getField "$line" "expiry_mm")
				expiryyy=$(getField "$line" "expiry_yy")
				notes=$(getField "$line" "notesPlain")
				cardtype=$(getLastField "$line" "type")
				pin=$(getLastField "$line" "pin")
				cvv=$(getLastField "$line" "cvv")
				phoneNum=$(getField "$line" "phoneLocal" | tr -d ' ')
				title=$(getLastField "$line" "title")
				path="ccards/$title"
				content="$ccnum\nBank: $bank\ncardType: $cardtype\nccNumber: $ccnum\nexpires: $expirymm/$expiryyy\nCVV: $cvv\nPIN: $pin\nnotes: $notes"
				
			elif [ "$type" == "securenotes.SecureNote" ]; then
				title=$(getField "$line" "title")
				content="\nNote: $(getField "$line" "notesPlain")"
				path="notes/$title"
			elif [ "$type" == "wallet.financial.BankAccountUS" ]; then
				bankName=$(getField "$line" "bankName")
				accountType=$(getField "$line" "accountType")
				iban=$(getField "$line" "iban")
				owner=$(getField "$line" "owner")
				title=$(getLastField "$line" "title")
				path="bank/$title"
				content="$iban\nBank: $bankName\niban: $iban\nKontoinhaber: $owner\nAccountType: $accountType"
			
			elif [ "$type" == "wallet.membership.RewardProgram" ]; then
				member_name=$(getField "$line" "member_name")
				company=$(getField "$line" "company_name")
				sinceMM=$(getField "$line" "member_since_mm")
				sinceYY=$(getField "$line" "member_since_yy")
				membershipNo=$(getField "$line" "membership_no")
				pin=$(getField "$line" "pin")
				title=$(getLastField "$line" "title")
				path="membership/$title"
				content="$pin\nName: $member_name\nMembership No: $membershipNo\nMember since: $sinceMM/$sinceYY\nPin: $pin"
				
			elif [ "$type" == "wallet.membership.Membership" ]; then
				membershipNo=$(getField "$line" "membership_no")
				memberName=$(getField "$line" "member_name")
				org_name=$(getField "$line" "org_name")
				title=$(getLastField "$line" "title")
				url=$(getField "$line" "website")
				
				path="membership/$title"
				content="$membershipNo\nMemberShipNo: $membershipNo\nMembershipName: $membershipName\nOrganisation: $org_name\nUrl: $url"
			elif [ "$type" == "wallet.computer.UnixServer" ]; then
				note=$(getField "$line" "notesPlain")
				adminPwd=$(getField "$line" "admin_console_password")
				password=$(getField "$line" "password")
				title=$(getLastField "$line" "title")
				username=$(getField "$line" "username")
				path="passwords/$title"
				content="$adminPwd\nUsername: $username\nPassword: $adminPwd\n Note: $note"
			elif [ "$type" == "wallet.computer.Router" ]; then
				dpassword=$(getField "$line" "disk_password")
				networkName=$(getField "$line" "network_name")
				password=$(getField "$line" "password")
				title=$(getLastField "$line" "title")
				name=$(getField "$line" "name")
				server=$(getField "$line" "server")
				wPassword=$(getField "$line" "wireless_password")
				wSecurity=$(getField "$line" "wireless_security")
				path="wifi/$title"
				content="$password\nDiskPassword: $dpassword\nNetworkName: $networkName\nName: $name\nServer: $server\nWireless Password: $wPAssword\nWireless Security: $wSecurity"
				
			elif [ "$type" == "identities.Identity" ]; then
				echo "Ignoring identity..."
				continue
			elif [ "$type" == "wallet.onlineservices.Email.v2" ]; then
				popAuth=$(getField "$line" "pop_authentication")
				popPwd=$(getField "$line" "pop_password")
				popSecurity=$(getField "$line" "pop_security")
				popServer=$(getField "$line" "pop_server")
				popType=$(getField "$line" "pop_type")
				popUser=$(getField "$line" "pop_username")
				title=$(getLastField "$line" "title")
				path="email/$title"
				content="$popPwd\nUsername: $popUser\nServer: $popServer\nType: $popType\nSecurity: $popSecurity\nAuth: $popAuth\nPassword: $popPwd"
			elif [ "$type" == "wallet.government.SsnUS" ]; then
				name=$(getField "$line" "name")
				number=$(getField "$line" "number")
				title=$(getLastField "$line" "title")
				path="id/$title"
				content="$number\nName: $name\nNumber: $number"
			elif [ "$type" == "wallet.computer.License" ]; then
				regCode=$(getField "$line" "reg_code")
				regEmail=$(getField "$line" "reg_email")
				regName=$(getField "$line" "reg_name")
				title=$(getLastField "$line" "title")
				path="licenses/$title"
				content="$regCode\nRegisteredEmail: $regEmail\nRegisteredName: $regName";
			else	
				echo "Unhandeled: '$type'"
				echo -e "$line\n" | json_pt $jsonOpts
			fi
			if [ "q$content" == "q" ]; then
				continue
			fi
			if [ $onlyTest -eq 1 ]; then
				echo -e "would insert to $path:\n$content"
			else 
				echo -e "$content" | pass insert -m -f "$path"
			fi
		fi
		#sleep 1
	fi
done  < $1
