# source me to have all the nice things

if [ "$0" == "$BASH_SOURCE" ]; then
    echo "You should be sourcing this."
    exit 1
fi

hscloud_root="$( cd "$(dirname "$BASH_SOURCE")"; pwd -P )"

hscloud-dc() {
    ( cd "$hscloud_root" && docker-compose -f "docker/docker-compose.yml" "$@" )
}

hscloud-pki-dev() {
    (
        set -e

        cd "$hscloud_root"
        rm -rf docker/pki

        cp -rv go/pki/dev-certs docker/pki
        cd docker/pki
        bash gen.sh m6220-proxy arista-proxy cmc-proxy topo client
        ls *pem
    )
}

hscloud-node-push-certs() {
    (
        set -e

        if [ -z "$1" ]; then
            echo >&2 "Usage: hscloud-node-push-certs node.fqdn.com"
            exit 1
        fi
        fqdn="$1"

        echo "Checking node livenes..."
        ssh root@$fqdn uname -a

        echo "Checking if node already has key..."
        ssh root@$fqdn stat /opt/hscloud/node.key || (
            echo "Generating key..."
            ssh root@$fqdn -- mkdir -p /opt/hscloud
            ssh root@$fqdn -- nix-shell -p openssl --command "\"openssl genrsa -out /opt/hscloud/node.key 4096\"" 
            ssh root@$fqdn -- chmod 400 /opt/hscloud/node.key
        )

        echo "Checking if node already has cert..."
        ssh root@$fqdn stat /opt/hscloud/node.crt && exit 0
        echo "No cert, will generate..."

        cd "$hscloud_root"
        secrets="$hscloud_root/secrets"
        ca="$secrets/plain/ca.key"
        [ ! -f "$ca" ] && ( scripts/secretstore decrypt "$secrets/cipher/ca.key" > $ca )

        ssh root@$fqdn -- nix-shell -p openssl --command "\"openssl req -new -key /opt/hscloud/node.key -out /opt/hscloud/node.csr -subj '/C=PL/ST=Mazowieckie/L=Mazowieckie/O=Stowarzyszenie Warszawski Hackerspace/OU=Node Bootstrap Certificate/CN="$fqdn"'\""
        scp root@$fqdn:/opt/hscloud/node.csr .
        openssl x509 -req -in node.csr -CA data/ca.crt -CAkey "$ca" -CAcreateserial -out "data/${fqdn}.crt"

        scp "data/${fqdn}.crt" root@$fqdn:/opt/hscloud/node.crt
        scp "data/ca.crt" root@$fqdn:/opt/hscloud/ca.crt
        ssh root@$fqdn -- chmod 444 /opt/hscloud/node.crt /opt/hscloud/ca.crt
        rm node.csr
    )
}

echo "Now playing:"
echo "  hscloud-dc      - run docker-compose"
echo "  hscloud-pki-dev - generate dev PKI certs"
echo "  hscloud-node-push-certs - push a node cert to the node"
echo ""
