#!/usr/bin/python3

import json
import base64
import qrcode
import subprocess
import argparse

parser = argparse.ArgumentParser(description='Generate a QR code of the shadowsocks-libev\'s config.')

parser.add_argument('-c', '--config', type=str, help='Choose a specific config file.', nargs='?')
parser.add_argument('-s', '--save-path', type=str, help='Choose a specific QR code name & path to save.', nargs='?')
parser.add_argument('-p', '--profile', type=str, help='Save the QR code with specified profile name.', nargs='?', default='default')
parser.add_argument('--no-open', dest='prompt_open', action='store_false', help='Do not prompt to open the QR code')

group = parser.add_mutually_exclusive_group()
group.add_argument('--ipv4', action='store_true', help='Using IPv4 IP address.')
group.add_argument('--ipv6', action='store_true', help='Using IPv6 IP address.')

args = parser.parse_args()

try:
    f = open(args.config)
except:
    f = open('config.json')
    print('== No specific config file. Using default (./config.json).')

config = json.load(f)
f.close()
encodestr = config['method'] + ':' + config['password']

if args.ipv4:
    srcstr = "ss://%s@%s:%s#%s" % (base64.b64encode(encodestr.encode()).decode(), config['server'], config['server_port'], args.profile)
    print(':: Using IPv4 IP address.')
elif args.ipv6:
    srcstr = "ss://%s@[%s]:%s#%s" % (base64.b64encode(encodestr.encode()).decode(), config['server'], config['server_port'], args.profile)
    print(':: Using IPv6 IP address.')
else:
    srcstr = "ss://%s@%s:%s#%s" % (base64.b64encode(encodestr.encode()).decode(), config['server'], config['server_port'], args.profile)
    print('== No specific IP address format. Using IPv4 IP address format.')

try:
    qrcode.make(srcstr).save(args.save_path)
    print(':: Image has been saved as %s !' % args.save_path)
except:
    qrcode.make(srcstr).save('image.png')
    print('== No specific image save path. Image has been saved as ./image.png !')

def ifopen():
    answer = input('>> Open the QR Code? [Y/n] ')
    if answer == "n" or answer == "N":
        exit(0)
    elif answer == "y" or answer == "Y":
        try:
            if args.save_path is not None:
                subprocess.Popen('xdg-open ' + args.save_path, shell=True)
            else:
                subprocess.Popen('xdg-open image.png', shell=True)
        except:
            subprocess.Popen('xdg-open image.png', shell=True)
    elif answer == "":
        try:
            if args.save_path is not None:
                subprocess.Popen('xdg-open ' + args.save_path, shell=True)
            else:
                subprocess.Popen('xdg-open image.png', shell=True)
        except:
            subprocess.Popen('xdg-open image.png', shell=True)
    else:
        print('!! Invalid option: ' + answer)
        ifopen()

if args.prompt_open:
    ifopen()
