#!/bin/sh /etc/rc.common
. /usr/bin/efuse.sh

START=50
USE_PROCD=1

build_random_key() {
	# Make a random 192-bit/24byte key and store it in a file
	PASSPHRASE=$(hexdump -vn24 -e '6/4 "%08X" 1 "\n"' /dev/urandom)
	PASSPHRASE=0x$PASSPHRASE
	echo "$PASSPHRASE" > /tmp/passphrase.txt

	# Insert key into efuses
	fuses_write "$PASSPHRASE"
}

start_service() {
    # Make a test directory on a filesystem that supports encryption
    [ -d /etc/ecryptfs ] || {
    mkdir -m 500 /etc/ecryptfs
    }
    [ -d /etc/.ecryptfs ] || {
    mkdir -m 700 /etc/.ecryptfs
    }

    # Read efuses
    PASSPHRASE=$(fuses_read)
    [ -z "$PASSPHRASE" ] && {
	build_random_key
    }
    [ "$PASSPHRASE" = "0x000000000000000000000000000000000000000000000000" ] && {
	build_random_key
    }

    mounted=$(mount | grep ecryptfs)
    [ -z "$mounted" ] && {
        # Read efuses
        PASSPHRASE=$(fuses_read)

        # Insert the key into the keyring
        RES=$(echo $PASSPHRASE | ecryptfs-add-passphrase)
        FILTER=$(echo ${RES%]*})
        SIG=$(echo ${FILTER#*\[})

        # Mount directory
        mount -t ecryptfs \
                /etc/.ecryptfs /etc/ecryptfs \
                -o "rw,key=passphrase:passphrase_passwd=$PASSPHRASE,ecryptfs_cipher=aes,ecryptfs_key_bytes=32,ecryptfs_passthrough=n,ecryptfs_enable_filename_crypto=y,ecryptfs_fnek_sig=$SIG,verbose=0,no_sig_cache"
    }

    # mv ssl stuff
    [ -d /etc/ecryptfs/ssl ] || {
    mkdir -m 500 /etc/ecryptfs/ssl
    }
    [ -f /etc/ecryptfs/ssl/keystore.p12 ] || {
	mv /etc/ssl/keystore.p12 /etc/ecryptfs/ssl/
	sync
    }
    # mv opkg stuff
    [ -d /etc/ecryptfs/opkg ] || {
    mkdir -m 500 /etc/ecryptfs/opkg
    }
    [ -f /etc/ecryptfs/opkg/opkg.conf ] || {
	cp /etc/opkg/opkg.conf /etc/ecryptfs/opkg/opkg.conf
	sync
    }
    # restart dependencie service
    /etc/init.d/uhttpd restart
}

stop_service() {
    # Now we remove the key
    keyctl clear @u
    #keyctl unlink @u
    # Unmount the directory
    umount /etc/ecryptfs
}

