#!/usr/bin/env bash
#
# Copyright (C) 2003 VA Linux Systems Japan, K.K. All rights reserved.
#
# LICENSE NOTICE
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#

set -e

eval `ultrapossum-config init`
tmp=`tempfile`
trap "/bin/rm -f $tmp; eval `ultrapossum-config term`" 0

home=$(getent passwd | egrep "^`whoami`:" | cut -d: -f6)
if test "x$home" = "x"; then
  home=$HOME
fi

#keygen <cmd>
keygen() {
  if ! test -f "$SSHKEYDIR/$1/id_rsa"; then
    install -d $SSHKEYDIR/$1
    ssh-keygen -t rsa -f $SSHKEYDIR/$1/id_rsa -N "" > /dev/null
  fi
}

#keyremove <cmd>
keyremove() {
  if ! test -f "$SSHKEYDIR/$1/id_rsa"; then
    echo "No such key: $1" 1>&2
    exit 1
  fi
  /bin/rm -f "$SSHKEYDIR/$1/id_rsa" "$SSHKEYDIR/$1/id_rsa.pub"
  /bin/rmdir "$SSHKEYDIR/$1" 2> /dev/null || true
  /bin/rmdir "$SSHKEYDIR/`dirname $1`" 2> /dev/null || true
}

list() {
  install -m 750 -d $SSHKEYDIR
  ( cd $SSHKEYDIR
    find . -name id_rsa | while read key
    do
      dirname $key | cut -d/ -f2-
    done )
}

auth() {
  add_startmark "##" "SSH" > $tmp
  list | while read cmd
  do
    if test -f $SSHKEYDIR/$cmd/id_rsa.pub; then
      echo "command=\"$MODULEDIR/$cmd\" `cat $SSHKEYDIR/$cmd/id_rsa.pub`" >> $tmp
    fi
  done
  add_endmark "##" "SSH" >> $tmp
  install -m700 -d $home/.ssh/
  touch $home/.ssh/authorized_keys
  add_end_vaconf $home/.ssh/authorized_keys $tmp "SSH"
}

unauth() {
  if test -f $home/.ssh/authorized_keys; then
    strip_vaconf $home/.ssh/authorized_keys "SSH"
  fi
}

# cmd <host> <cmd>
cmd() {
  getconfig | ssh -T -i $SSHKEYDIR/$2/id_rsa $1 $MODULEDIR/$2
}

case "x$1" in
  xkeygen|xkeyremove)
    if test "x$2" = "x"; then
      echo "Usage: $0 $1 <cmd>" 1>&2
      exit 1
    fi
    if test "x$1" = "xkeygen"; then install -m 750 -d $SSHKEYDIR; fi
    "$1" "$2"
    ;;
  xlist|xauth|xunauth)
    $1
    ;;
  xcmd)
    if test "x$3" = "x"; then
      echo "Usage: $0 cmd <host> <cmd>" 1>&2
      exit 1
    fi
    cmd "$2" "$3"
    ;;
  x)
    echo "Usage: $0 keygen <cmd>|keyremove <cmd>|list|auth|unauth|cmd <host> <cmd>" 1>&2
    ;;
  x*)
    echo "Unknown argument: $1" 1>&2
    exit 1
    ;;
esac

