#!/bin/sh
set -e

# Common environment variables
#



check_keystore () {
  if [ ! -d ${KEYSTORE} ]
  then
    mkdir -p ${KEYSTORE}
  fi
}

check_bastionkey () {
  if [ ! -f ${BASTIONKEY} ]
  then
    ssh-keygen -o -a 100 -t ed25519 -f ${BASTIONKEY} -N "" -C bastion@${NAME}
    cp -p ${BASTIONKEY}.pub ${KEYSTORE}/_b${NAME}.pub
    cp -p ${BASTIONKEY}.pub ${KEYSTORE}/_d${NAME}.pub
  fi
}

check_gitkey () {
  if [ ! -f ${GITKEY} ]
  then
    ssh-keygen -o -a 100 -t ed25519 -f ${GITKEY} -N "" -C git@${NAME}
  fi
}

check_rsynckey () {
  if [ ! -f ${RSYNCKEY} ]
  then
    ssh-keygen -o -a 100 -t ed25519 -f ${RSYNCKEY} -N "" -C rsync@${NAME}
    cp -p ${RSYNCKEY}.pub ${KEYSTORE}/_r${NAME}.pub
  fi
}

check_vibblerkey () {
  if [ ! -f ${VIBBLERKEY} ]
  then
    ssh-keygen -o -a 100 -t ed25519 -f ${VIBBLERKEY} -N "" -C vibbler@${NAME}
    cp -p ${VIBBLERKEY}.pub ${KEYSTORE}/_v${NAME}.pub
  fi
}

check_key () {
  if [ ! -f ${KEYSTORE}/${KEYNAME} ]
  then
    ssh-keygen -o -a 100 -t ed25519 -f ${KEYSTORE}/${KEYNAME} -N "" -C ${KEYNAME}@${MACHINENAME}
  fi
  cp -p ${KEYSTORE}/${KEYNAME}.pub ${KEYSTORE}/${KEYNAME_SHORT}${MACHINENAME}.pub
}

#####
# Main script below
#####
KEYSTORE=~/.mykeys
BASTIONKEY=${KEYSTORE}/bastionkey
GITKEY=${KEYSTORE}/gitkey
RSYNCKEY=${KEYSTORE}/rsynckey
VIBBLERKEY=${KEYSTORE}/vibblerkey


if [ -d /zTools/zShared/shared ] && [ ! -d /static ] 
then
	BASE=/zTools/zShared
  echo ${BASE}
fi

if [ -d /zz/zShared/shared ] && [ ! -d /static ] 
then
	BASE=/zz/zShared
  echo ${BASE}
fi

if [ ! -d /zz/zShared/shared ] && [ ! -d /zTools/zShared/shared ] && [ -d /static ]
then
	BASE=/static
  echo ${BASE}
fi


MYNAME=$(uname -n)
if [ -d /volume12/zTools/Sync${MYNAME}/zTools/zShared ]
then
	BASE=/volume12/zTools/Sync${MYNAME}/zTools/zShared
  echo ${BASE}
fi

if [ -z ${BASE+x} ]
then
  echo "Can not find BASE directory"
  exit 1
fi

if [ -f ${BASE}/shared/myshared ]
then
  . ${BASE}/shared/myshared
fi

SHARED=${BASE}/shared

. ${SHARED}/myshared

NAME=$(uname -n|cut -c2-4)
LAST=$(uname -n| sed -e 's/.*\(.$\)/\1/')
NAME=$(uname -n)
LAST=$(uname -n)

check_keystore
# check_bastionkey

# check_gitkey
# check_rsynckey
# check_vibblerkey


MACHINENAME=$(uname -n)
PREFIX=_1
ID=$(id -u)

# for github
KEYNAME=github
KEYNAME_SHORT=${PREFIX}gh${ID}
check_key

KEYNAME=githubdeploy
KEYNAME_SHORT=${PREFIX}ghdeploy${ID}
check_key

KEYNAME=githubwrite
KEYNAME_SHORT=${PREFIX}ghwrite${ID}
check_key

KEYNAME=gitea
KEYNAME_SHORT=${PREFIX}gt${ID}
check_key

KEYNAME=giteadeploy
KEYNAME_SHORT=${PREFIX}gtdeploy${ID}
check_key

KEYNAME=giteawrite
KEYNAME_SHORT=${PREFIX}gtwrite${ID}
check_key

KEYNAME=bastion
KEYNAME_SHORT=${PREFIX}$(echo $KEYNAME|cut -c1-2)${ID}
check_key

KEYNAME=rsync
KEYNAME_SHORT=${PREFIX}$(echo $KEYNAME|cut -c1-2)${ID}
check_key

KEYNAME=vibbler
KEYNAME_SHORT=${PREFIX}$(echo $KEYNAME|cut -c1-2)${ID}
check_key