#!/usr/bin/python


import os, sys



ip_proxys = []


f = open("vps.txt", "rb")


if f is None:

    print "Error to open file (vps.txt)\n"

    sys.exit()


for line in f:

    line = line.strip()

    result = line.split('\t')

    if len(result) != 2:

        continue

    name   = result[0].strip()

    ipaddr = result[1].strip()

    if name == "" or ipaddr == "":

        continue

    ip_proxys.append( ipaddr )

f.close()


if 0 == len(ip_proxys):

    print "No IP!\n"

    sys.exit()


cur_ip = ""

f = open("cur.txt", "rb")

if f is None:

    pass

else:

    line = f.readline()

    cur_ip = line.strip()

    f.close()


next_index = 0


if cur_ip != "" and cur_ip in ip_proxys:

    next_index = ip_proxys.index(cur_ip) + 1


if  next_index >= len(ip_proxys):

    next_index = 0


#start_proxy_host = 'vps3'

start_proxy_host = ip_proxys[ next_index ]

f = open("cur.txt", "wb")

f.write(start_proxy_host)

f.write("\r\n")

f.close()


start_proxy_port = 10888


cmd = 'sudo -u *** autossh -M 2000 -N -v ***@'

cmd += start_proxy_host

cmd += ' -D 0.0.0.0:'

cmd += str(start_proxy_port)

cmd += ' >/dev/null 2>&1 &'


rt = os.system(cmd)


if rt == 0:

    print '+++ok+++'