#!/usr/bin/env pike import .util; import Getopt; int main(int ac, array(string) av) { array options = find_all_options(av, ({ ({ list_topics, NO_ARG, "-f" }), ({ match_pattern, HAS_ARG, "-m" }), }) ); array args = get_args(av)[1..]; mapping my_cnf = ini(combine_path(getenv("HOME"), ".my.cnf"))->client; if(!my_cnf || !my_cnf->user || !my_cnf->password || !my_cnf->database) throw(({"Error: check $HOME/.my.cnf", backtrace()})); string sqlspec = sprintf("mysql://%s\:%s@%s/%s", my_cnf->user, my_cnf->password, my_cnf->host || "localhost", my_cnf->database); Sql.Sql db = Sql.Sql(sqlspec); if(!sizeof(options)) { if(!sizeof(args)) { simple_fetch(db); return 0; } fetch_by_topic(db, args); return 0; } foreach(options, array o) { o[0](db, o[1], args); } return 0; } void simple_fetch(object db) { int howmany = (int)((db->query("select count(*) from fortunes")[0])["count(*)"]); string fortune = db->query("select data from fortunes where id=%d", random(howmany-1)+1)[0]->data; write(fortune); } void fetch_by_topic(object db, array args) { write("%O\n", args); } void list_topics(object db, mixed...args) { write(`*(sort(map(db->query("select topic from ftopics"), `[], "topic")), "\n") + "\n"); } void match_pattern(object db, string pattern, array args) { if(!sizeof(args)) { array res = db->query("select data from fortunes where data rlike %s", pattern); if(!sizeof(res)) return; write(`*(map(res, `[], "data"), "%\n") ); } else { foreach(args, string topic) { array tres = db->query("select topic_id from ftopics where topic=%s", topic); if(!sizeof(tres)) continue; string topic_id = tres[0]["topic_id"]; array res = db->query("select data from fortunes where topic_id=%s and data rlike %s", topic_id, pattern); if(!sizeof(res)) continue; werror("(%s)\n", topic); write(`*(map(res, `[], "data"), "%\n")+"%\n"); } } }