#!/usr/bin/env python
from __future__ import print_function
import sys
import os

histsize = 100000
histname = ".directory_history"
home = os.path.expanduser('~')
histfile = os.path.join(home, histname)


def remove_duplicates(commands):
    cmds = []
    for cmd in reversed(commands):
        if cmd not in cmds:
            cmds.append(cmd)
    return list(reversed(cmds))


def get_commands(directory):
    commands = []
    try:
        with open(histfile, "r") as f:
            continued = False
            for i, line in enumerate(f.readlines()):
                line = line.rstrip('\n')
                if not continued and not line.endswith('\\'):
                    try:
                        cmd_dir, command = line.split(";", 1)
                    except ValueError:
                        continue
                elif continued and line.endswith('\\'):
                    command += line[:-1] + r'\\n'
                    continue
                elif continued:
                    command += line
                    continued = False
                else:  # line ends with backslash
                    try:
                        cmd_dir, command = line.split(";", 1)
                        command = command[:-1] + r'\\n'
                        continued = True
                        continue
                    except ValueError:
                        continued = False
                        continue

                if cmd_dir == directory and len(commands) < histsize:
                    commands.append(command)
    except IOError:
        open(histfile, 'a').close()

    return remove_duplicates(commands)


if __name__ == '__main__':
    try:
        print('\n'.join(get_commands(sys.argv[1])))
    except IndexError:
        print('\n'.join(get_commands(os.getcwd())))
