List all queued and running jobs or only those with
    an optional 'tag'.

    CLI Example:

    .. code-block:: bash

        salt '*' at.atq
        salt '*' at.atq [tag]
        salt '*' at.atq [job number]

def atq(tag=None):
    '''
    List all queued and running jobs or only those with
    an optional 'tag'.

    CLI Example:

    .. code-block:: bash

        salt '*' at.atq
        salt '*' at.atq [tag]
        salt '*' at.atq [job number]
    '''
    jobs = []

    res = __salt__['cmd.run_all']('atq')

    if res['retcode'] > 0:
        return {'error': res['stderr']}

    # No jobs so return
    if res['stdout'] == 'no files in queue.':
        return {'jobs': jobs}

    # Jobs created with at.at() will use the following
    # comment to denote a tagged job.
    job_kw_regex = re.compile(r'^### SALT: (\w+)')

    # Split each job into a dictionary and handle
    # pulling out tags or only listing jobs with a certain
    # tag
    for line in res['stdout'].splitlines():
        job_tag = ''

        # skip header
        if line.startswith(' Rank'):
            continue

        # parse job output
        tmp = line.split()
        timestr = ' '.join(tmp[1:5])
        job = tmp[6]
        specs = datetime.datetime(
            *(time.strptime(timestr, '%b %d, %Y %H:%M')[0:5])
        ).isoformat().split('T')
        specs.append(tmp[7])
        specs.append(tmp[5])

        # make sure job is str
        job = six.text_type(job)

        # search for any tags
        atjob_file = '/var/spool/cron/atjobs/{job}'.format(
            job=job
        )
        if __salt__['file.file_exists'](atjob_file):
            with salt.utils.files.fopen(atjob_file, 'r') as atjob:
                for line in atjob:
                    line = salt.utils.stringutils.to_unicode(line)
                    tmp = job_kw_regex.match(line)
                    if tmp:
                        job_tag = tmp.groups()[0]

        # filter on tags
        if not tag:
            jobs.append({'job': job, 'date': specs[0], 'time': specs[1],
                'queue': specs[2], 'user': specs[3], 'tag': job_tag})
        elif tag and tag in [job_tag, job]:
            jobs.append({'job': job, 'date': specs[0], 'time': specs[1],
                'queue': specs[2], 'user': specs[3], 'tag': job_tag})

    return {'jobs': jobs}