#!/bin/bash
if [[ $# -ne 3 || ("$2" != "analyst" && "$2" != "owner" && "$2" != "desktop") ]]; then
  echo "USAGE: $0 username analyst|owner|desktop vmdelete"
  exit 1
fi

if [[ $(psql -d ossdip -U postgres -tA -c "SELECT COUNT(*) FROM users WHERE username = '$1'") -lt 1 ]]; then
  echo "User does not exists in DB"
  logger "Failed to create vm for user ${1} since it does not exist"
  exit 1
fi

id=""
vnc_pass=""
vnc_hash=""
if [[ "$2" == "desktop" ]]; then
  vnc_pass=$(/opt/users/bin/mkpasswd 8 8)
  vnc_hash=$(echo $vnc_pass | vncpasswd -f | base64)
fi

pass=$(/opt/users/bin/mkpasswd 12 3)
hash=$(/opt/users/bin/mkpasshash $pass $(/opt/users/bin/mksalt))
if [[ "$2" == "desktop" ]]; then
  psql -d ossdip -U postgres -tAq -c "call create_desktop_vm('$1','$pass','$hash','$vnc_pass','$vnc_hash','$3')"
  if [[ "$?" -ne 0 ]]; then
    exit 1
  fi
  id=$(psql -d ossdip -U postgres -tAq -c "SELECT last_value as id FROM sq_desktop")
elif [[ "$2" == "analyst" ]]; then
  psql -d ossdip -U postgres -tAq -c "call create_analyst_vm('$1','$pass','$hash','$3')"
  if [[ "$?" -ne 0 ]]; then
    exit 2
  fi
  id=$(psql -d ossdip -U postgres -tAq -c "SELECT last_value as id FROM sq_analyst")
elif [[ "$2" == "owner" ]]; then
  psql -d ossdip -U postgres -tAq -c "call create_owner_vm('$1','$pass','$hash','$3')"
  if [[ "$?" -ne 0 ]]; then
    exit 3
  fi
  id=$(psql -d ossdip -U postgres -tAq -c "SELECT last_value as id FROM sq_owner")
fi
logger "Create new vm type ${2} for user ${1}, received id ${id}"
echo "$id"
