#!/usr/bin/python2
# -*- coding: utf-8 -*-
u"Remove scripts and data files which were installed by setup.py"
from __future__ import print_function
import os
import argparse
import subprocess
from functools import reduce
MYPROGNAME=os.path.basename(__file__)
RM_DIRS=['/bin/rm', '-r']
RM_FILES=['/bin/rm']
def cmd_list_to_string(cmd_list):
    "Convert list of command args, to command string"
    return reduce(lambda cstr, carg: cstr + ' ' + carg, cmd_list[1:], cmd_list[0])

VERSION_STRING="ssh_certificate-0.02benchrelease_python2.7"
REMOVEDIRS=[
    "/usr/local/lib/python2.7/dist-packages/ssh_certificate"
]
REMOVEFILES=[
    "/usr/local/bin/limited-passwordfree-sudo", 
    "/usr/local/bin/ssh_certificate_uninstall", 
    "/usr/local/bin/cert_setup", 
    "/usr/local/bin/derive_pubkey", 
    "/usr/local/bin/certssh", 
    "/etc/ssh_certificate/certdbase.tar", 
    "/etc/ssh_certificate/ssh_certificate_defaults.json", 
    "/usr/local/var/ssh_certificate/content.tar", 
    "/usr/local/lib/python2.7/dist-packages/ssh_certificate-0.02benchrelease_python2.7.egg-info"
]
PURGE_DIRS=[
    "/etc/ssh_certificate", 
    "/usr/local/var/ssh_certificate"
]
if __name__ == '__main__':
    PARSER = argparse.ArgumentParser(prog=MYPROGNAME, description=__doc__)
    PARSER.add_argument('-d', '--dry-run', dest='dry_run', action='store_true',
                        help="Show the commands to uninstall but don't invoke them.")
    PARSER.add_argument('-p', '--purge', dest='purge', action='store_true',
                        help="Also remove these directories recursively:{}.".format(PURGE_DIRS))
    PARSER.add_argument('-t', '--tarball', dest='tarball', action='store_true',
                        help="Print the tarball this uninstall is out of.")
    PARSER.add_argument('-v', '--version', dest='version', action='store_true',
                        help="Print the package version this uninstall applies to.")
    ARGS = PARSER.parse_args()
    removedirs_cmd = RM_DIRS + REMOVEDIRS
    removefiles_cmd = RM_FILES + REMOVEFILES
    purge_dirs_cmd = RM_DIRS + PURGE_DIRS
    if ARGS.tarball:
       print("{}.tar.gz".format(VERSION_STRING))
    elif ARGS.version:
       print(VERSION_STRING)
    elif ARGS.dry_run:
        if len(REMOVEDIRS) > 0:
            print(cmd_list_to_string(removedirs_cmd))
        if len(REMOVEFILES) > 0:
            print(cmd_list_to_string(removefiles_cmd))
        if len(PURGE_DIRS) > 0 and ARGS.purge:
            print(cmd_list_to_string(purge_dirs_cmd))
    else:
        if len(REMOVEDIRS) > 0:
            print(cmd_list_to_string(removedirs_cmd))
            subprocess.check_call(removedirs_cmd)
        if len(REMOVEFILES) > 0:
            print(cmd_list_to_string(removefiles_cmd))
            subprocess.check_call(removefiles_cmd)
        if len(PURGE_DIRS) > 0 and ARGS.purge:
            print(cmd_list_to_string(purge_dirs_cmd))
            subprocess.check_call(purge_dirs_cmd)

