#!/bin/bash
# Merge pubkey into ~/.ssh/authorized_keys

host="$2"

[ -d ~/.ssh ] || mkdir ~/.ssh
auth_file=`realpath ~/.ssh/authorized_keys`
auth_file2=`realpath ~/.ssh/authorized_keys2`
pubkeydir=/unas/etc/dualcontroller/pubkeys

case "$1" in
    add)
        pubkey=`cat "/tmp/$host.pub"`

        if [ -n "$pubkey" ];then
            sed -i "/ dualcontroller@$host\$/d" "$auth_file"
            echo "$pubkey" >> "$auth_file"
        fi

        rm "/tmp/$host.pub"
    ;;
    merge)
        cat $pubkeydir/*.pub > "$auth_file2"
    ;;
    rm)
        sed -i "/ dualcontroller@$host\$/d" "$auth_file" "$auth_file2"
        rm $pubkeydir/$host.pub
    ;;
    leave)
        sed -i "/ dualcontroller@\S*\$/d" "$auth_file" "$auth_file2"
        rm $pubkeydir/*
    ;;
    *)
        echo "Unknown command: $1"
    ;;
esac
