#!/usr/bin/env python3

import sys
from os.path import dirname, abspath, join
import subprocess

# Note this does not resolve symbolic links
# https://stackoverflow.com/a/17806123
FIREFOX_BINARY = join(dirname(abspath(__file__)), 'firefox')

argvs = list(sys.argv)
argvs[0] = FIREFOX_BINARY

# geckdriver will run `firefox -version` first to check the version
if len(sys.argv) == 2 and sys.argv[1] == '-version':
    subprocess.check_call(argvs)
    exit(0)

# First search for the -tmpprofile option
new_profile_path = None
for idx, argv in enumerate(sys.argv):
    if argv == '-tmpprofile':
        new_profile_path = sys.argv[idx + 1]
        break
# If it's present, replace profile with tmp_profile
if new_profile_path:
    for idx, argv in enumerate(sys.argv):
        if argv == '-profile':
            old_profile_path = sys.argv[idx + 1]
            subprocess.check_call(['rm', '-r', new_profile_path])
            subprocess.check_call(['cp', '-r', old_profile_path, new_profile_path])
            argvs[idx+1] = new_profile_path
            break

# Firefox will ignore the -tmpprofile option
subprocess.check_call(argvs)

[((36, 0, 36, 28), 'subprocess.check_call', 'subprocess.check_call', ({(36, 22, 36, 27): 'argvs'}, {}), '(argvs)', False, 'import subprocess\n'), ((16, 4, 16, 32), 'subprocess.check_call', 'subprocess.check_call', ({(16, 26, 16, 31): 'argvs'}, {}), '(argvs)', False, 'import subprocess\n'), ((9, 30, 9, 47), 'os.path.abspath', 'abspath', ({(9, 38, 9, 46): '__file__'}, {}), '(__file__)', False, 'from os.path import dirname, abspath, join\n'), ((30, 12, 30, 65), 'subprocess.check_call', 'subprocess.check_call', ({(30, 34, 30, 64): "['rm', '-r', new_profile_path]"}, {}), "(['rm', '-r', new_profile_path])", False, 'import subprocess\n'), ((31, 12, 31, 83), 'subprocess.check_call', 'subprocess.check_call', ({(31, 34, 31, 82): "['cp', '-r', old_profile_path, new_profile_path]"}, {}), "(['cp', '-r', old_profile_path, new_profile_path])", False, 'import subprocess\n')]