[
  {
    "path": "CSharp/Hangover.cs",
    "content": "﻿namespace Hacker_Scripts\n{\n    using System;\n    using Twilio;\n    using System.Linq;\n\n    class Hangover\n    {\n        public static string TWILIO_ACCOUNT_SID = Environment.GetEnvironmentVariable(\"TWILIO_ACCOUNT_SID\");\n        public static string AUTH_TOKEN = Environment.GetEnvironmentVariable(\"TWILIO_AUTH_TOKEN\");\n\n        public static string YOUR_NUMBER = \"9879789978\";\n        public static string BOSS_NUMBER = \"3213213233\";\n\n        static void Main(string[] args)\n        {\n            var twilio = new TwilioRestClient(TWILIO_ACCOUNT_SID, AUTH_TOKEN);\n\n            string[] randomMessages = {\n                \"Locked out\",\n                \"Pipes broke\",\n                \"Food poisoning\",\n                \"Not feeling well\"\n            };\n\n            int randomIndex = new Random().Next(randomMessages.Count());\n            String messageToSend = (randomMessages[randomIndex]);\n\n            var message = twilio.SendMessage(YOUR_NUMBER, BOSS_NUMBER, messageToSend);\n            Console.WriteLine(message.Sid);\n        }\n    }\n}\n\n"
  },
  {
    "path": "CSharp/SmackMyBitch.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Twilio;\n\nnamespace Hacker_Scripts\n{\n    class SmackMyBitch\n    {\n        public static string TWILIO_ACCOUNT_SID = Environment.GetEnvironmentVariable(\"TWILIO_ACCOUNT_SID\");\n        public static string AUTH_TOKEN = Environment.GetEnvironmentVariable(\"TWILIO_AUTH_TOKEN\");\n\n        public static string YOUR_NUMBER = \"9879789978\";\n        public static string HER_NUMBER = \"3213213233\";\n\n        static void Main(string[] args)\n        {\n            var twilio = new TwilioRestClient(TWILIO_ACCOUNT_SID, AUTH_TOKEN);\n\n            string[] randomMessages = {\n                \"Working hard\",\n                \"Gotta ship this feature\",\n                \"Someone fucked the system again\"\n            };\n\n            int randomIndex = new Random().Next(randomMessages.Count());\n            String messageToSend = (randomMessages[randomIndex]);\n\n            var message = twilio.SendMessage(YOUR_NUMBER, HER_NUMBER, messageToSend);\n            Console.WriteLine(message.Sid);\n        }\n    }\n}\n"
  },
  {
    "path": "R/hangover.R",
    "content": "library(httr)\n\ntoday = Sys.Date()\n\n# skip weekends\nif( weekdays(today) %in% c('Saturday','Sunday') ){\n  quit()\n  }\n\n# exit if no sessions with my username are found\noutput = system(\"who\", intern = TRUE)\nif( !( grep('^my_user_name', output) ) ){\n  quit()\n  }\n\n# returns 'None' if the key doesn't exist\nTWILIO_ACCOUNT_SID = Sys.getenv('TWILIO_ACCOUNT_SID')\nTWILIO_AUTH_TOKEN  = Sys.getenv('TWILIO_AUTH_TOKEN')\n\n# Phone numbers\nmy_number = '+xxx'\nnumber_of_boss= '+xxx'\n\nexcuse = c(\n  'Locked out',\n  'Pipes broke',\n  'Food poisoning',\n  'Not feeling well'\n      )\n\nPOST(paste(\"https://api.twilio.com/2010-04-01/Accounts/\",TWILIO_ACCOUNT_SID,\"/Messages.json\",sep=\"\"),\n          body = list(From=my_number,To=number_of_boss,Body=paste(\"Gonna work from home. \", sample(excuse,1))),\n\t            authenticate(TWILIO_ACCOUNT_SID,TWILIO_AUTH_TOKEN) )\n\nprint( paste(\"Message sent at\",Sys.time()) )\n"
  },
  {
    "path": "R/smack_my_bitch_up.R",
    "content": "library(httr)\n\ntoday = Sys.Date()\n\n# skip weekends\nif( weekdays(today) %in% c('Saturday','Sunday') ){\n  quit()\n  }\n\n# exit if no sessions with my username are found\noutput = system(\"who\", intern = TRUE)\nif( !( grep('^my_user_name', output) ) ){\n  quit()\n  }\n\n# returns 'None' if the key doesn't exist\nTWILIO_ACCOUNT_SID = Sys.getenv('TWILIO_ACCOUNT_SID')\nTWILIO_AUTH_TOKEN  = Sys.getenv('TWILIO_AUTH_TOKEN')\n\n# Phone numbers\nmy_number = '+xxx'\nher_number = '+xxx'\n\nreasons = c(\n  'Working hard',\n    'Gotta ship this feature',\n      'Someone fucked the system again'\n      )\n\nPOST(paste(\"https://api.twilio.com/2010-04-01/Accounts/\",TWILIO_ACCOUNT_SID,\"/Messages.json\",sep=\"\"),\n          body = list(From=my_number,To=her_number,Body=paste(\"Late at work. \", sample(reasons,1))),\n\t            authenticate(TWILIO_ACCOUNT_SID,TWILIO_AUTH_TOKEN) )\n\nprint( paste(\"Message sent at\",Sys.time()) )\n"
  },
  {
    "path": "README.md",
    "content": "\nEnglish | [简体中文](./README.zh-CN.md)\n\n# Hacker Scripts\n\nBased on a _[true\nstory](https://www.jitbit.com/alexblog/249-now-thats-what-i-call-a-hacker/)_:\n\n> xxx: OK, so, our build engineer has left for another company. The dude was literally living inside the terminal. You know, that type of a guy who loves Vim, creates diagrams in Dot and writes wiki-posts in Markdown... If something - anything - requires more than 90 seconds of his time, he writes a script to automate that.\n\n> xxx: So we're sitting here, looking through his, uhm, \"legacy\"\n\n> xxx: You're gonna love this\n\n> xxx: [`smack-my-bitch-up.sh`](https://github.com/NARKOZ/hacker-scripts/blob/master/smack-my-bitch-up.sh) - sends a text message \"late at work\" to his wife (apparently). Automatically picks reasons from an array of strings, randomly. Runs inside a cron-job. The job fires if there are active SSH-sessions on the server after 9pm with his login.\n\n> xxx: [`kumar-asshole.sh`](https://github.com/NARKOZ/hacker-scripts/blob/master/kumar-asshole.sh) - scans the inbox for emails from \"Kumar\" (a DBA at our clients). Looks for keywords like \"help\", \"trouble\", \"sorry\" etc. If keywords are found - the script SSHes into the clients server and rolls back the staging database to the latest backup. Then sends a reply \"no worries mate, be careful next time\".\n\n> xxx: [`hangover.sh`](https://github.com/NARKOZ/hacker-scripts/blob/master/hangover.sh) - another cron-job that is set to specific dates. Sends automated emails like \"not feeling well/gonna work from home\" etc. Adds a random \"reason\" from another predefined array of strings. Fires if there are no interactive sessions on the server at 8:45am.\n\n> xxx: (and the oscar goes to) [`fucking-coffee.sh`](https://github.com/NARKOZ/hacker-scripts/blob/master/fucking-coffee.sh) - this one waits exactly 17 seconds (!), then opens a telnet session to our coffee-machine (we had no frikin idea the coffee machine is on the network, runs linux and has a TCP socket up and running) and sends something like `sys brew`. Turns out this thing starts brewing a mid-sized half-caf latte and waits another 24 (!) seconds before pouring it into a cup. The timing is exactly how long it takes to walk to the machine from the dudes desk.\n\n> xxx: holy sh*t I'm keeping those\n\nOriginal: http://bash.im/quote/436725 (in Russian)  (Archive.org [link](https://web.archive.org/web/20210226092253/http://bash.im/quote/436725))\nPull requests with other implementations (Python, Perl, Shell, etc) are welcome.\n\n## Usage\n\nYou need these environment variables:\n\n```sh\n# used in `smack-my-bitch-up` and `hangover` scripts\nTWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nTWILIO_AUTH_TOKEN=yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\n\n# used in `kumar_asshole` script\nGMAIL_USERNAME=admin@example.org\nGMAIL_PASSWORD=password\n```\n\nFor Ruby scripts you need to install gems:\n`gem install dotenv twilio-ruby gmail`\n\n## Cron jobs\n\n```sh\n# Runs `smack-my-bitch-up.sh` monday to friday at 9:20 pm.\n20 21 * * 1-5 /path/to/scripts/smack-my-bitch-up.sh >> /path/to/smack-my-bitch-up.log 2>&1\n\n# Runs `hangover.sh` monday to friday at 8:45 am.\n45 8 * * 1-5 /path/to/scripts/hangover.sh >> /path/to/hangover.log 2>&1\n\n# Runs `kumar-asshole.sh` every 10 minutes.\n*/10 * * * * /path/to/scripts/kumar-asshole.sh\n\n# Runs `fucking-coffee.sh` hourly from 9am to 6pm on weekdays.\n0 9-18 * * 1-5 /path/to/scripts/fucking-coffee.sh\n```\n\n---\nCode is released under WTFPL.\n"
  },
  {
    "path": "README.zh-CN.md",
    "content": "# Hacker Scripts\n\n根据 *[真实故事](https://www.jitbit.com/alexblog/249-now-thats-what-i-call-a-hacker/)*  改编:\n\n> xxx: 是这样的，我们的构建工程师离职去了另外一家公司，这货基本算是生活在终端里。 你知道么，这人热爱Vim，用Dot作图，甚至用MarkDown来写维基帖子...，如果有什么事情要花上他超过90秒，他一定会整个脚本来让这件事变得“自动化”。\n\n> xxx: 我们现在坐在他的工位上，看着他留下来的这些，呃，“遗产”？\n\n> xxx: 我觉得你们会喜欢这些的\n\n> xxx: [`smack-my-bitch-up.sh(拍老婆马屁脚本)`](https://github.com/NARKOZ/hacker-scripts/blob/master/smack-my-bitch-up.sh) - 它会给他的老婆（很明显是他老婆）发送一条“今晚要加班了”的短信，再自动从文本库中随机地选择一条理由。这个脚本被设置为定时触发，而且只有在工作日晚9点以后，服务器上还有他登陆的SSH进程在运行时才会执行。\n\n> xxx: [`kumar-asshole.sh（库马尔个傻*）`](https://github.com/NARKOZ/hacker-scripts/blob/master/kumar-asshole.sh) - 这个脚本会自动扫描邮箱，如果发现其中有库马尔（库马尔是我们客户公司的一位数据库管理员）发来的邮件，就会在其中寻找关键字如“求助”，“遇到麻烦了”，“抱歉”等等，如果发现了这些关键字，这个脚本会通过SSH连接上客户公司的服务器，把中间数据库（staging database）回滚到最新一次的可用备份。然后它会给邮件发送回复，“没事了哥们，下次小心点哈”。\n\n> xxx: [`hangover.sh（宿醉）`](https://github.com/NARKOZ/hacker-scripts/blob/master/hangover.sh) - 同样是个定时执行的任务，被设置为在特定日期触发，它会自动发送诸如“今天不太舒服”或“今天我在家上班”之类的邮件，同样会从文本库里随机选取一条理由。这个任务会在工作日清晨8点45分以后服务器上仍然没有可交互的SSH进程时真正执行。\n\n> xxx: (最牛的就是接下来这个) [`fucking-coffee.sh（**的咖啡）`](https://github.com/NARKOZ/hacker-scripts/blob/master/fucking-coffee.sh) - 这个脚本在启动之后，会先等待恰好17秒（！），然后启动一个登录进程连接到我们的咖啡机（淦，我们之前完全不知道我们的咖啡机是联网的，上面还运行着Linux系统，甚至还跑着TCP socket连接！），然后它会发送类似“系统！开始煮咖啡！”之类的消息，结果这条消息会让咖啡机开始工作，煮一杯 中杯大小、半咖啡因的拿铁，再等待恰好24秒（！）后，才倒进咖啡杯里。这些时间加起来刚好就是这位程序员从自己的工位走到机器前要的时间。\n\n> xxx: 天了噜我要把这些保留下来。\n\n原文: http://bash.im/quote/436725 (俄语)\n\n欢迎使用其它语言来实现 (Python, Perl, Shell等等)并提交PR。\n\n## 用法\n\n你需要以下这些环境变量：\n\n```bash\n# used in `smack-my-bitch-up` and `hangover` scripts\nTWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nTWILIO_AUTH_TOKEN=yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\n\n# used in `kumar_asshole` script\nGMAIL_USERNAME=admin@example.org\nGMAIL_PASSWORD=password\n```\n\n为了执行Ruby脚本，你需要安装gems: `gem install dotenv twilio-ruby gmail`\n\n## 定时任务\n\n```bash\n# Runs `smack-my-bitch-up.sh` monday to friday at 9:20 pm.\n20 21 * * 1-5 /path/to/scripts/smack-my-bitch-up.sh >> /path/to/smack-my-bitch-up.log 2>&1\n\n# Runs `hangover.sh` monday to friday at 8:45 am.\n45 8 * * 1-5 /path/to/scripts/hangover.sh >> /path/to/hangover.log 2>&1\n\n# Runs `kumar-asshole.sh` every 10 minutes.\n*/10 * * * * /path/to/scripts/kumar-asshole.sh\n\n# Runs `fucking-coffee.sh` hourly from 9am to 6pm on weekdays.\n0 9-18 * * 1-5 /path/to/scripts/fucking-coffee.sh\n```\n\n------\n\n代码的使用遵循WTFPL（Do What The Fuck You Want To Public License）协议。\n"
  },
  {
    "path": "clojure/coffee.clj",
    "content": "(ns hacker-scripts.coffee\n  (:require [environ.core :refer [env]])\n  (:import\n    (java.net Socket)\n    (java.io BufferedReader PrintWriter InputStreamReader)))\n\n(def my-username \"my-username\")\n(def my-password \"my-password\")\n\n(def coffee-machine-ip \"10.10.42.42\")\n(def password-prompt \"Password: \")\n(def connection-port 23)\n\n(def sec-delay-before-brew 17)\n(def sec-delay-before-pour 24)\n\n(defn logged-in? [] (= (:USER env) my-username))\n\n(defn auth [in-stream out-stream]\n  (if (= (.readLine in-stream) password-prompt)\n    (.println out-stream my-password)\n    (throw (RuntimeException.\n             \"Failed to authenticate with coffee machine\"))))\n\n(defn command-brew-pour [out-stream]\n  (do\n    (Thread/sleep (* 1000 sec-delay-before-brew))\n    (.println out-stream \"sys brew\")\n    (Thread/sleep (* 1000 sec-delay-before-pour))\n    (.println out-stream \"sys pour\")))\n\n(defn coffee []\n  (if (logged-in?)\n    (with-open [socket (Socket. coffee-machine-ip connection-port)\n                out-stream (PrintWriter. (.getOutputStream socket) true)\n                in-stream (BufferedReader. (InputStreamReader. (.getInputStream socket)))]\n      (do\n        (auth in-stream out-stream)\n        (command-brew-pour out-stream)))))\n"
  },
  {
    "path": "clojure/hangover.clj",
    "content": "(ns hacker-scripts.hangover\n  (:import\n    (com.twilio Twilio)\n    (com.twilio.rest.api.v2010.account Message)\n    (com.twilio.type PhoneNumber)))\n\n(def acc-sid \"my twilio account SID\")\n(def acc-tkn \"my twilio secret token\")\n\n(def my-num (PhoneNumber. \"+10001112222\"))\n(def boss-num (PhoneNumber. \"+19998887777\"))\n\n(def reasons [\"Receiving delivery\"\n              \"Waiting for repairman\"\n              \"Nasty cold\"])\n\n(defn twilio-init []\n  (Twilio/init acc-sid acc-tkn))\n\n(defn send-sms [to-num from-num message]\n  (.. Message (creator to-num from-num message) create))\n\n(def send-sms-boss (partial send-sms boss-num my-num))\n\n(defn hangover []\n  (twilio-init)\n  (let [message (rand-nth reasons)]\n    (send-sms-boss message)))\n"
  },
  {
    "path": "clojure/kumar.clj",
    "content": "(ns hacker-scripts.kumar\n  (:import\n    (java.util Properties)\n    (javax.mail Session Authenticator PasswordAuthentication Message$RecipientType Transport Folder Flags Flags$Flag)\n    (javax.mail.internet MimeMessage InternetAddress)\n    (javax.mail.search FlagTerm FromTerm AndTerm OrTerm SubjectTerm BodyTerm SearchTerm)))\n\n(def host \"smtp.gmail.com\")\n(def my-email \"my-email@gmail.com\")\n(def my-password \"my-gmail-password\")\n(def kumar-email \"kumar@gmail.com\")\n\n(def seen-flag (Flags. (Flags$Flag/SEEN)))\n\n(def unread-term (FlagTerm. seen-flag false))\n\n(defn get-session []\n  (let [authenticator (proxy [Authenticator] []\n                        (getPasswordAuthentication []\n                          (PasswordAuthentication. my-email my-password)))\n        props (Properties.)]\n    (.put props \"mail.smtp.host\" \"smtp.gmail.com\")\n    (.put props \"mail.smtp.port\" \"587\")\n    (.put props \"mail.smtp.auth\" \"true\")\n    (.put props \"mail.smtp.starttls.enable\" \"true\")\n    (.. Session (getInstance props authenticator))))\n\n(defn get-inbox [session]\n  (let [store (.getStore session \"imaps\")\n        inbox (do\n                (.connect store host my-email my-password)\n                (.getFolder store \"inbox\"))]\n    (.open inbox Folder/READ_WRITE)\n    inbox))\n\n(defn get-no-worries-message [session]\n  (let [message (MimeMessage. session)]\n    (.setFrom message (InternetAddress. my-email))\n    (.addRecipient message Message$RecipientType/TO (InternetAddress. kumar-email))\n    (.setSubject message \"Database fixes\")\n    (.setText message \"No worries mate, be careful next time\")\n    message))\n\n(defn search-term [pattern]\n  (OrTerm. (into-array SearchTerm [(SubjectTerm. pattern) (BodyTerm. pattern)])))\n\n(defn any-of-search-term [& patterns]\n  (OrTerm. (into-array (map search-term patterns))))\n\n(defn from-term [addr]\n  (FromTerm. (InternetAddress. addr)))\n\n(defn get-unread-sos-from-kumar [inbox]\n  (let [flag (AndTerm. (into-array SearchTerm [unread-term\n                                               (from-term kumar-email)\n                                               (any-of-search-term \"help\" \"sorry\" \"trouble\")]))]\n    (.search inbox flag)))\n\n(defn mark-as-read [inbox messages]\n  (.setFlags inbox messages seen-flag true))\n\n(defn kumar-asshole []\n  (let [session (get-session)\n        inbox (get-inbox session)\n        unread-sos-from-kumar (get-unread-sos-from-kumar inbox)]\n    (when (seq unread-sos-from-kumar)\n      (mark-as-read inbox unread-sos-from-kumar)\n      (Transport/send (get-no-worries-message session)))))\n"
  },
  {
    "path": "clojure/smack.clj",
    "content": "(ns hacker-scripts.smack\n  (:import\n    (com.twilio Twilio)\n    (com.twilio.rest.api.v2010.account Message)\n    (com.twilio.type PhoneNumber)))\n\n(def acc-sid \"my twilio account SID\")\n(def acc-tkn \"my twilio secret token\")\n\n(def my-num (PhoneNumber. \"+10001112222\"))\n(def her-num (PhoneNumber. \"+19998887777\"))\n\n(def reasons [\"Working hard\"\n              \"Gotta ship this feature\"\n              \"Someone fucked the system again\"])\n\n(defn twilio-init []\n  (Twilio/init acc-sid acc-tkn))\n\n(defn send-sms [to-num from-num message]\n  (.. Message (creator to-num from-num message) create))\n\n(def send-sms-girlfriend (partial send-sms her-num my-num))\n\n(defn smack []\n  (twilio-init)\n  (let [message (rand-nth reasons)]\n    (send-sms-girlfriend message)))\n"
  },
  {
    "path": "coffee/fucking.coffee",
    "content": "#!/usr/bin/env coffee\n\nusername = 'name'\n\nhost = 'localhost'\nport = '3000'\npass = '5555'\n\nsh = require('child_process').execSync\n\n# weekend\nprocess.exit 0 if new Date().getDay() in [6, 0]\n\n# no sessions\nprocess.exit 0 unless new RegExp(username).test sh('who -q').toString()\n\nconn = require('net').createConnection port, host\n\nsetTimeout ->\n  conn.write \"#{pass}\\nsys brew\\n\"\n  setTimeout ->\n    conn.end 'sys pour'\n    process.exit 0\n  , 2 * 1000\n, 1 * 1000\n\n# alert\nsh 'say come here and take your fucking coffee'\n"
  },
  {
    "path": "fucking-coffee.sh",
    "content": "#!/bin/sh\n#\n# Requires fucking_coffee script in your bin\n#\n\nexec fucking_coffee\n"
  },
  {
    "path": "fucking_coffee.rb",
    "content": "#!/usr/bin/env ruby\n\n# Exit early if no sessions with my username are found\nexit unless `who -q`.include? ENV['USER']\n\nrequire 'net/telnet'\n\ncoffee_machine_ip = '10.10.42.42'\npassword = '1234'\npassword_prompt = 'Password: '\ndelay_before_brew = 17\ndelay = 24\n\nsleep delay_before_brew\ncon = Net::Telnet.new('Host' => coffee_machine_ip)\ncon.cmd('String' => password, 'Match' => /#{password_prompt}/)\ncon.cmd('sys brew')\nsleep delay\ncon.cmd('sys pour')\ncon.close\n"
  },
  {
    "path": "go/fucking-coffee.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com/codeskyblue/go-sh\"\n\t\"github.com/google/goexpect\"\n)\n\nfunc main() {\n\t// exit early if no sessions with my username are found\n\tcurrentUser, _ := sh.Command(\"who\").Command(\"grep\", \"my_username\").Output()\n\tif currentUser == nil {\n\t\tos.Exit(1)\n\t}\n\n\t// info about the coffee machine\n\tcoffeeMachineIP := \"10.10.42.42\"\n\tpassword := \"1234\"\n\tpasswordPrompt := \"Password: \"\n\tdelayBeforeBrew := 17 * time.Second\n\tdelay := 24 * time.Second\n\n\t// timeout for the telnet prompts\n\ttimeout := 10 * time.Minute\n\n\t// sleep 17 seconds before brewing coffee\n\ttime.Sleep(delayBeforeBrew)\n\n\t// spawn a new telnet session with the coffee machine\n\tt, _, err := expect.Spawn(fmt.Sprintf(\"telnet %s\", coffeeMachineIP), -1)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer t.Close()\n\n\tt.Expect(regexp.MustCompile(passwordPrompt), timeout)\n\tt.Send(password + \"\\n\")\n\tt.Expect(regexp.MustCompile(\"telnet>\"), timeout)\n\tt.Send(\"sys brew\\n\")\n\ttime.Sleep(delay)\n\tt.Expect(regexp.MustCompile(\"telnet>\"), timeout)\n\tt.Send(\"sys pour\\n\")\n\tt.Expect(regexp.MustCompile(\"telnet>\"), timeout)\n\tt.Send(\"exit\\n\")\n}\n"
  },
  {
    "path": "go/hangover.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\n\t\"github.com/codeskyblue/go-sh\"\n\t\"github.com/subosito/twilio\"\n)\n\nconst my_number string = \"+xxxxx\"\nconst boss_number string = \"+yyyyy\"\n\nfunc main() {\n\t//exit if sessions with my username are found\n\t_, err := sh.Command(\"who\").Command(\"grep\", \"my_username\").Output()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\t//Grab Twilio ID and token from environment variables\n\tAccount_Sid := os.Getenv(\"TWILIO_ACCOUNT_SID\")\n\tAuth_Token := os.Getenv(\"TWILIO_AUTH_TOKEN\")\n\n\t//create the reasons slice and append reasons to it\n\treasons := make([]string, 0)\n\treasons = append(reasons,\n\t\t\"Locked out\",\n\t\t\"Pipes broke\",\n\t\t\"Food poisoning\",\n\t\t\"Not feeling well\")\n\n\t// Initialize Twilio client and send message\n\tclient := twilio.NewClient(Account_Sid, Auth_Token, nil)\n\tmessage := fmt.Sprint(\"Gonna work from home...\", reasons[rand.Intn(len(reasons))])\n\n\tparams := twilio.MessageParams{\n\t\tBody: message,\n\t}\n\ts, resp, err := client.Messages.Send(my_number, boss_number, params)\n\n\tif err == nil {\n\t\tlog.Fatal(s, resp, err)\n\t}\n}\n"
  },
  {
    "path": "go/smack_my_bitch_up.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\toutput1, err := exec.Command(\"who\").Output()\n\toutput2 := os.Getenv(\"USER\")\n\tusers := string(output1[:])\n\tcurrent_user := string(output2[:])\n\tif !strings.Contains(users, current_user) {\n\t\treturn\n\t}\n\n\treasons := []string{\"Working hard\", \"Gotta ship this feature\", \"Someone fucked the system again\"}\n\n\trand.Seed(time.Now().UTC().UnixNano())\n\tmessage := \"Late at work. \" + reasons[rand.Intn(len(reasons))]\n\n\tTWILIO_ACCOUNT_SID := string(os.Getenv(\"TWILIO_ACCOUNT_SID\"))\n\tTWILIO_AUTH_TOKEN := string(os.Getenv(\"TWILIO_AUTH_TOKEN\"))\n\tMY_NUMBER := string(os.Getenv(\"MY_NUMBER\"))\n\tHER_NUMBER := string(os.Getenv(\"HER_NUMBER\"))\n\n\tresponse, err := exec.Command(\"curl\", \"-fSs\", \"-u\", TWILIO_ACCOUNT_SID+\":\"+TWILIO_AUTH_TOKEN, \"-d\", \"From=\"+MY_NUMBER, \"-d\", \"To=\"+HER_NUMBER, \"-d\", \"Body=\"+message, \"https://api.twilio.com/2010-04-01/Accounts/\"+TWILIO_ACCOUNT_SID+\"/Messages\").Output()\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to send SMS: %s\", err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Message Sent Successfully with response: %s \", response)\n}\n"
  },
  {
    "path": "groovy/fucking_coffee.groovy",
    "content": "@Grab(group='org.hidetake', module='groovy-ssh', version='1.1.8')\n@GrabExclude('org.codehaus.groovy:groovy-all')\nimport org.hidetake.groovy.ssh.Ssh\n\nfinal def ssh = Ssh.newService()\n\nfinal def HOST = '10.10.42.42'\nfinal def USER = 'my_username'\nfinal def PASSWORD = '1234'\nfinal def DELAY = 24\n\nssh.remotes {\n    webServer {\n        host = HOST\n        user = USER\n        password = PASSWORD\n    }\n}\n\nssh.run {\n    session(ssh.remotes.webServer) {\n        execute 'sys brew'\n        execute \"sleep ${DELAY}s\"\n        execute 'sys pour'\n    }\n}\n"
  },
  {
    "path": "hangover.rb",
    "content": "#!/usr/bin/env ruby\n\n# Exit early if sessions with my username are found\nexit if `who -q`.include? ENV['USER']\n\nrequire 'dotenv'\nrequire 'twilio-ruby'\n\nDotenv.load\n\nTWILIO_ACCOUNT_SID = ENV['TWILIO_ACCOUNT_SID']\nTWILIO_AUTH_TOKEN  = ENV['TWILIO_AUTH_TOKEN']\n\n@twilio = Twilio::REST::Client.new TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN\n\n# Phone numbers\nmy_number      = '+xxx'\nnumber_of_boss = '+xxx'\n\nexcuse = [\n  'Locked out',\n  'Pipes broke',\n  'Food poisoning',\n  'Not feeling well'\n].sample\n\n# Send a text message\n@twilio.messages.create(\n  from: my_number, to: number_of_boss,\n  body: \"Gonna work from home. #{excuse}\"\n)\n\n# Log this\nputs \"Message sent at: #{Time.now} | Excuse: #{excuse}\"\n"
  },
  {
    "path": "hangover.sh",
    "content": "#!/bin/sh -e\n\n# Exit early if any session with my username is found\nif who | grep -wq $USER; then\n  exit\nfi\n\n# Phone numbers\nMY_NUMBER='+xxx'\nNUMBER_OF_BOSS='+xxx'\n\nEXCUSES=(\n  'Locked out'\n  'Pipes broke'\n  'Food poisoning'\n  'Not feeling well'\n)\nrand=$[ $RANDOM % ${#EXCUSES[@]} ]\n\nRANDOM_EXCUSE=${EXCUSES[$rand]}\nMESSAGE=\"Gonna work from home. \"$RANDOM_EXCUSE\n\n# Send a text message\nRESPONSE=`curl -fSs -u \"$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN\" \\\n  -d \"From=$MY_NUMBER\" -d \"To=$NUMBER_OF_BOSS\" -d \"Body=$MESSAGE\" \\\n  \"https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages\"`\n\n# Log errors\nif [ $? -gt 0 ]; then\n  echo \"Failed to send SMS: $RESPONSE\"\n  exit 1\nfi\n"
  },
  {
    "path": "java/FuckingCoffee.java",
    "content": "import java.net.*;\nimport java.io.*;\n \npublic class FuckingCoffee{\n\n    private static final String MY_USERNAME = \"my_username\";\n    private static final String PASSWORD_PROMPT = \"Password: \";\n    private static final String PASSWORD = \"1234\";\n    private static final String COFFEE_MACHINE_IP = \"10.10.42.42\";\n    private static int DELAY_BEFORE_BREW = 17;\n    private static int DELAY = 24;\n    \n    public static void main(String[] args)throws Exception{\n        for(int i =  1; i< args.length ; i++){\n            if(!args[i].contains(MY_USERNAME)){\n                return;\n            }\n        }\n        Socket telnet = new Socket(COFFEE_MACHINE_IP, 23);\n        PrintWriter out = new PrintWriter(telnet.getOutputStream(), true);\n        BufferedReader in = new BufferedReader(new InputStreamReader(telnet.getInputStream()));\n        Thread.sleep(DELAY_BEFORE_BREW*1000);\n        if(!in.readLine().equals(PASSWORD_PROMPT)){\n            return ;\n        }\n        out.println(PASSWORD);\n        out.println(\"sys brew\");\n        Thread.sleep(DELAY*1000);\n        out.println(\"sys pour\");\n        out.close();\n        in.close();\n        telnet.close();\n    }\n}\n"
  },
  {
    "path": "java/Hangover.java",
    "content": "import com.twilio.sdk.TwilioRestClient;\nimport com.twilio.sdk.TwilioRestException;\nimport com.twilio.sdk.resource.factory.MessageFactory;\nimport com.twilio.sdk.resource.instance.Message;\nimport org.apache.http.NameValuePair;\nimport org.apache.http.message.BasicNameValuePair;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\n\npublic class Hangover {\n\n    public static final String ACCOUNT_SID = System.getenv(\"TWILIO_ACCOUNT_SID\");\n    public static final String AUTH_TOKEN = System.getenv(\"TWILIO_AUTH_TOKEN\");\n\n    public static final String YOUR_NUMBER = \"1231231231\";\n    public static final String BOSS_NUMBER = \"3213213213\";\n\n    public static void main(String[] args) throws TwilioRestException {\n\n        TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);\n\n        String[] randomMessages = {\n                \"Locked out\",\n                \"Pipes broke\",\n                \"Food poisoning\",\n                \"Not feeling well\"\n        };\n\n        int randomIndex = new Random().nextInt(randomMessages.length);\n        String finalMessage = (randomMessages[randomIndex]);\n\n        List<NameValuePair> params = new ArrayList<NameValuePair>();\n        params.add(new BasicNameValuePair(\"Body\", \"Gonna work from home. \" + finalMessage));\n        params.add(new BasicNameValuePair(\"From\", YOUR_NUMBER));\n        params.add(new BasicNameValuePair(\"To\", BOSS_NUMBER));\n\n        MessageFactory messageFactory = client.getAccount().getMessageFactory();\n        Message message = messageFactory.create(params);\n        System.out.println(message.getSid());\n    }\n}\n\n"
  },
  {
    "path": "java/KumarAsshole.java",
    "content": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.util.*;\nimport java.util.regex.*;\n\nimport javax.mail.*;\nimport javax.mail.internet.*;\nimport javax.mail.search.FlagTerm;\n//Dependencies- Java mail API \n\npublic class KumarAsshole {\n\n\tpublic static void main(String[] args) {\n\t\tKumarAsshole asshole = new KumarAsshole();\n\t\tasshole.read();\n\t}\n\n\tpublic void read() {\n\t\tProperties props = new Properties();\n\n\t\t//modify below properties to your details\n\t\tString host = \"smtp.gmail.com\";\n\t\tString username = \"yourmailaddress@example.com goes here\";\n\t\tString password = \"your password goes here \";\n\t\tString Kumar_mail = \"the mail address to be replied to !\";\n\n\t\ttry {\n\t\t\tSession session = Session.getDefaultInstance(props, null);\n\n\t\t\tStore store = session.getStore(\"imaps\");\n\t\t\tstore.connect(host, username, password);\n\n\t\t\tFolder inbox = store.getFolder(\"inbox\");\n\t\t\tinbox.open(Folder.READ_ONLY);\n\n\t\t\tMessage messages[] = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));\n\n\t\t\tfor (int i = 0; i < messages.length; i++) {\n\t\t\t\tif (messages[i].getFrom()[0].toString().contains(Kumar_mail)) {\n\t\t\t\t\tString bodytext = null;\n\t\t\t\t\tObject content = messages[i].getContent();\n\t\t\t\t\tif (content instanceof String) {\n\t\t\t\t\t\tbodytext = (String) content;\n\t\t\t\t\t} else if (content instanceof Multipart) {\n\t\t\t\t\t\tMultipart mp = (Multipart) content;\n\n\t\t\t\t\t\tBodyPart bp = mp.getBodyPart(mp.getCount() - 1);\n\t\t\t\t\t\tbodytext = (String) bp.getContent();\n\t\t\t\t\t}\n\n\t\t\t\t\tPattern pattern = Pattern.compile(\"sorry|help|wrong\", Pattern.CASE_INSENSITIVE);\n\t\t\t\t\tMatcher matcher = pattern.matcher(bodytext);\n\t\t\t\t\t// check all occurance\n\n\t\t\t\t\tif (matcher.find()) {\n\t\t\t\t\t\tProperties props1 = new Properties();\n\t\t\t\t\t\tAddress[] tomail;\n\n\t\t\t\t\t\tMimeMessage msg = new MimeMessage(session);\n\t\t\t\t\t\tmsg.setFrom(new InternetAddress(username));\n\t\t\t\t\t\ttomail = messages[i].getFrom();\n\t\t\t\t\t\tString t1 = tomail[0].toString();\n\t\t\t\t\t\tmsg.addRecipient(Message.RecipientType.TO, new InternetAddress(t1));\n\t\t\t\t\t\tmsg.setSubject(\"Database fixes\");\n\t\t\t\t\t\tmsg.setText(\"No problem. I've fixed it. \\n\\n Please be careful next time.\");\n\t\t\t\t\t\tTransport t = null;\n\t\t\t\t\t\tt = session.getTransport(\"smtps\");\n\t\t\t\t\t\tt.connect(host, username, password);\n\t\t\t\t\t\tt.sendMessage(msg, msg.getAllRecipients());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinbox.close(true);\n\t\t\tstore.close();\n\n\t\t} catch(Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "java/SmackMyBitch.java",
    "content": "import com.twilio.sdk.TwilioRestClient;\nimport com.twilio.sdk.TwilioRestException;\nimport com.twilio.sdk.resource.factory.MessageFactory;\nimport com.twilio.sdk.resource.instance.Message;\nimport org.apache.http.NameValuePair;\nimport org.apache.http.message.BasicNameValuePair;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\n\n//Pre-requisite apache http and twilio java libraries\n\n\npublic class SmackMyBitch {\n\n    public static final String ACCOUNT_SID = System.getenv(\"TWILIO_ACCOUNT_SID\");\n    public static final String AUTH_TOKEN = System.getenv(\"TWILIO_AUTH_TOKEN\");\n\n    public static final String YOUR_NUMBER = \"1231231231\";\n    public static final String HER_NUMBER = \"3213213213\";\n\n    public static void main(String[] args) throws TwilioRestException {\n\n        TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);\n\n        String[] randomMessages = {\n                \"Working hard\",\n                \"Gotta ship this feature\",\n                \"Someone fucked the system again\",\n        };\n\n        int randomIndex = new Random().nextInt(randomMessages.length);\n        String finalMessage = (randomMessages[randomIndex]);\n\n        List<NameValuePair> params = new ArrayList<NameValuePair>();\n        params.add(new BasicNameValuePair(\"Body\", \"Late at work. \" + finalMessage));\n        params.add(new BasicNameValuePair(\"From\", YOUR_NUMBER));\n        params.add(new BasicNameValuePair(\"To\", HER_NUMBER));\n\n        MessageFactory messageFactory = client.getAccount().getMessageFactory();\n        Message message = messageFactory.create(params);\n        System.out.println(message.getSid());\n    }\n}"
  },
  {
    "path": "kotlin/FuckingCoffee.kt",
    "content": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.io.PrintWriter\nimport java.net.Socket\n\nprivate const val MY_USERNAME = \"my_username\"\nprivate const val PASSWORD_PROMPT = \"Password: \"\nprivate const val PASSWORD = \"1234\"\nprivate const val COFFEE_MACHINE_IP = \"10.10.42.42\"\nprivate const val DELAY_BEFORE_BREW = 17\nprivate const val DELAY = 24\n\nfun main(args: Array<String>) {\n    for (i in 1 until args.size) {\n        if (!args[i].contains(MY_USERNAME)) {\n            return\n        }\n    }\n    val telnet = Socket(COFFEE_MACHINE_IP, 23)\n    val out = PrintWriter(telnet.getOutputStream(), true)\n    val reader = BufferedReader(InputStreamReader(telnet.getInputStream()))\n    Thread.sleep((DELAY_BEFORE_BREW * 1000).toLong())\n    if (reader.readLine() != PASSWORD_PROMPT) {\n        return\n    }\n    out.println(PASSWORD)\n    out.println(\"sys brew\")\n    Thread.sleep((DELAY * 1000).toLong())\n    out.println(\"sys pour\")\n    out.close()\n    reader.close()\n    telnet.close()\n}"
  },
  {
    "path": "kotlin/Hangover.kt",
    "content": "import com.twilio.sdk.TwilioRestClient\nimport com.twilio.sdk.TwilioRestException\nimport com.twilio.sdk.resource.factory.MessageFactory\nimport com.twilio.sdk.resource.instance.Message\nimport org.apache.http.NameValuePair\nimport org.apache.http.message.BasicNameValuePair\n\nimport java.util.ArrayList\nimport java.util.Random\n\nprivate val ACCOUNT_SID = System.getenv(\"TWILIO_ACCOUNT_SID\")\nprivate val AUTH_TOKEN = System.getenv(\"TWILIO_AUTH_TOKEN\")\n\nprivate const val YOUR_NUMBER = \"1231231231\"\nprivate const val BOSS_NUMBER = \"3213213213\"\n\nprivate val randomMessages = arrayOf(\n    \"Locked out\",\n    \"Pipes broke\",\n    \"Food poisoning\",\n    \"Not feeling well\"\n)\n\n\nfun main() {\n\n    val client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)\n\n    val finalMessage = randomMessages.random()\n\n    val params = ArrayList<NameValuePair>().apply {\n        add(BasicNameValuePair(\"Body\", \"Gonna work from home. $finalMessage\"))\n        add(BasicNameValuePair(\"From\", YOUR_NUMBER))\n        add(BasicNameValuePair(\"To\", BOSS_NUMBER))\n    }\n\n    val messageFactory = client.getAccount().getMessageFactory()\n    val message = messageFactory.create(params)\n    System.out.println(message.getSid())\n}\n\n"
  },
  {
    "path": "kotlin/KumarAsshole.kt",
    "content": "import java.io.File\nimport java.io.FileInputStream\nimport java.util.*\nimport java.util.regex.*\n\nimport javax.mail.*\nimport javax.mail.internet.*\nimport javax.mail.search.FlagTerm\n\n//modify below properties to your details\nprivate const val host = \"smtp.gmail.com\"\nprivate const val username = \"yourmailaddress@example.com goes here\"\nprivate const val password = \"your password goes here \"\nprivate const val Kumar_mail = \"the mail address to be replied to !\"\n\n\n//Dependencies- Java mail API\nfun main() {\n    val asshole = KumarAsshole()\n    asshole.read()\n}\n\nobject KumarAsshole {\n\n    fun read() {\n        val props = Properties()\n\n        try {\n\n            val session = Session.getDefaultInstance(props, null)\n\n            val store = session.getStore(\"imaps\")\n            store.connect(host, username, password)\n\n            val inbox = store.getFolder(\"inbox\")\n            inbox.open(Folder.READ_ONLY)\n\n            val messages = inbox.search(FlagTerm(Flags(Flags.Flag.SEEN), false))\n\n            for (i in messages.indices) {\n\n                if (messages[i].getFrom()[0].toString().contains(Kumar_mail)) {\n\n                    var bodytext: String? = null\n                    val content = messages[i].getContent()\n                    if (content is String) {\n                        bodytext = content\n\n                    } else if (content is Multipart) {\n\n                        val mp = content as Multipart\n\n                        val bp = mp.getBodyPart(mp.getCount() - 1)\n                        bodytext = bp.getContent()\n\n                    }\n\n                    val pattern = Pattern.compile(\"sorry|help|wrong\", Pattern.CASE_INSENSITIVE)\n                    val matcher = pattern.matcher(bodytext!!)\n                    // check all occurance\n\n                    if (matcher.find()) {\n\n                        val props1 = Properties()\n                        val tomail: Array<Address>\n\n                        val msg = MimeMessage(session)\n                        msg.setFrom(InternetAddress(username))\n                        tomail = messages[i].getFrom()\n                        val t1 = tomail[0].toString()\n                        msg.addRecipient(Message.RecipientType.TO, InternetAddress(t1))\n                        msg.setSubject(\"Database fixes\")\n                        msg.setText(\"No problem. I've fixed it. \\n\\n Please be careful next time.\")\n                        var t: Transport? = null\n                        t = session.getTransport(\"smtps\")\n                        t!!.connect(host, username, password)\n                        t!!.sendMessage(msg, msg.getAllRecipients())\n                    }\n\n\n                }\n            }\n            inbox.close(true)\n            store.close()\n\n        } catch (e: Exception) {\n            e.printStackTrace()\n        }\n\n    }\n}"
  },
  {
    "path": "kotlin/SmackMyBitch.kt",
    "content": "import com.twilio.sdk.TwilioRestClient\nimport com.twilio.sdk.TwilioRestException\nimport com.twilio.sdk.resource.factory.MessageFactory\nimport com.twilio.sdk.resource.instance.Message\nimport org.apache.http.NameValuePair\nimport org.apache.http.message.BasicNameValuePair\n\nimport java.util.ArrayList\nimport java.util.Random\n\n//Pre-requisite apache http and twilio java libraries\n\nprivate const val ACCOUNT_SID = System.getenv(\"TWILIO_ACCOUNT_SID\")\nprivate const val AUTH_TOKEN = System.getenv(\"TWILIO_AUTH_TOKEN\")\n\nprivate const val YOUR_NUMBER = \"1231231231\"\nprivate const val HER_NUMBER = \"3213213213\"\n\nprivate val randomMessages = arrayOf(\n    \"Working hard\",\n    \"Gotta ship this feature\",\n    \"Someone fucked the system again\"\n)\n\n\n@Throws(TwilioRestException::class)\nfun main() {\n\n    val client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)\n\n    val finalMessage = randomMessages.random()\n\n    val params = mutableListOf<NameValuePair>().apply {\n        add(BasicNameValuePair(\"Body\", \"Late at work. $finalMessage\"))\n        add(BasicNameValuePair(\"From\", YOUR_NUMBER))\n        add(BasicNameValuePair(\"To\", HER_NUMBER))\n    }\n\n    val messageFactory = client.getAccount().getMessageFactory()\n    val message = messageFactory.create(params)\n    System.out.println(message.getSid())\n}"
  },
  {
    "path": "kumar-asshole.sh",
    "content": "#!/bin/sh\n#\n# Requires kumar_asshole script in your bin\n#\n\nexec kumar_asshole\n"
  },
  {
    "path": "kumar_asshole.rb",
    "content": "#!/usr/bin/env ruby\n\nrequire 'dotenv'\nrequire 'gmail'\n\nDotenv.load\n\nGMAIL_USERNAME = ENV['GMAIL_USERNAME']\nGMAIL_PASSWORD = ENV['GMAIL_PASSWORD']\n\nGMAIL = Gmail.connect(GMAIL_USERNAME, GMAIL_PASSWORD)\nKUMARS_EMAIL = 'kumar.a@example.com'\n\nDB_NAME_REGEX  = /\\S+_staging/\nKEYWORDS_REGEX = /sorry|help|wrong/i\n\ndef create_reply(subject)\n  GMAIL.compose do\n    to KUMARS_EMAIL\n    subject \"RE: #{subject}\"\n    body \"No problem. I've fixed it. \\n\\n Please be careful next time.\"\n  end\nend\n\nGMAIL.inbox.find(:unread, from: KUMARS_EMAIL).each do |email|\n  if email.body.raw_source[KEYWORDS_REGEX] && (db_name = email.body.raw_source[DB_NAME_REGEX])\n    backup_file = \"/home/backups/databases/#{db_name}-\" + (Date.today - 1).strftime('%Y%m%d') + '.gz'\n    abort 'ERROR: Backup file not found' unless File.exist?(backup_file)\n\n    # Restore DB\n    `gunzip -c #{backup_file} | psql #{db_name}`\n\n    # Mark as read, add label and reply\n    email.read!\n    email.label('Database fixes')\n    reply = create_reply(email.subject)\n    GMAIL.deliver(reply)\n  end\nend\n"
  },
  {
    "path": "nodejs/fucking_coffee.js",
    "content": "#!/usr/bin/env node\n\n/* Before running:\n        npm install telnet-client\n*/\n\nvar exec = require('child_process').exec;\nvar telnet = require('telnet-client');\n\nvar me = 'my_username';\n\nexec(\"who\", function(error, stdout, stderr) {\n\n    // Exit if no sessions with my username are found\n    if(stdout.indexOf(me) == -1)\n        process.exit(/*1*/);\n\n    var coffee_machine_ip = 'xxx.xxx.xxx.xxx';\n    var password = 'xxxx';\n    var con = new telnet();\n\n    con.on('ready', function(prompt) {\n        con.exec('Password: ' + password, function(error, res) {\n\n            // Brew Coffee!\n            con.exec('sys brew', function(error, res) {\n\n                // Wait for 24s\n                setTimeout(function() {\n\n                    // Pour Coffee!\n                    con.exec('sys pour', function(error, res) {\n                        con.end();\n                    });\n                }, 24000);\n            });\n        });\n    });\n\n    con.connect({host: coffee_machine_ip});\n});\n"
  },
  {
    "path": "nodejs/fucking_coffee_yo_server.js",
    "content": "#!/usr/bin/env node\n\n/* Before running:\n        Setup Yo Callback URL and Yo username for coffee machine:\n        http://docs.justyo.co/docs/receiving-a-yo-with-the-api\n*/\n\nvar exec = require('child_process').exec;\nvar telnet = require('telnet-client');\n\nvar ME = 'my_username';\nvar AUTHORIZED_YO_NAMES = [ME];\nvar COFFEE_MACHINE_YO_NAME = 'coffeemachine';\n\n// These should be same as what you set up in the Yo API\nvar CALLBACK_URL = 'http://xxx.com';\nvar CALLBACK_ENDPOINT = '/coffeemachine';\n\nvar PORT = '3000';\n\nexec(\"who -q\", function(error, stdout, stderr) {\n\n    var express = require('express');\n    var coffeeApp = express();\n\n    // Exit if no sessions with my username are found\n    if(stdout.indexOf(ME) == -1)\n        process.exit(1);\n\n    // Got a Yo!\n    coffeeApp.get(CALLBACK_ENDPOINT, function (req, res) {\n\n        if(req.query.username === undefined) {\n            // Not a Yo, don't make coffee.\n            res.sendStatus(401);\n        }\n        else if(AUTHORIZED_YO_NAMES.indexOf(req.query.username) == -1) {\n            // If authorized users didn't Yo, don't make coffee.\n            res.sendStatus(401);\n\n            console.log(req.query.username + ' YO\\'d.')\n        }\n        else {\n            res.sendStatus(200);\n\n            var coffee_machine_ip = 'xxx.xxx.xxx.xxx';\n            var password = 'xxxx';\n            var con = new telnet();\n\n            con.on('ready', function(prompt) {\n                con.exec('Password: ' + password, function(error, res) {\n\n                    // Brew Coffee!\n                    con.exec('sys brew', function(error, res) {\n\n                        // Wait for 24s\n                        setTimeout(function() {\n\n                            // Pour Coffee!\n                            con.exec('sys pour', function(error, res) {\n                                con.end();\n                            });\n                        }, 24000);\n                    });\n                });\n            });\n\n            con.connect({host: coffee_machine_ip});\n        }\n    });\n\n    // Not Callback endpoint\n    coffeeApp.get('/*', function (req, res) {\n        res.sendStatus(404);\n    });\n\n    var coffeeServer = coffeeApp.listen(PORT, CALLBACK_URL, function() {\n        console.log('Coffee Server listening at %s:%s',\n            CALLBACK_URL, PORT);\n        console.log('\\nYo Callback URL: %s:%s/%s', \n            CALLBACK_URL, PORT, CALLBACK_ENDPOINT);\n    });\n});\n"
  },
  {
    "path": "nodejs/hangover.js",
    "content": "#!/usr/bin/env node\n\n/* Before running:\n        npm install twilio\n*/\n\nvar exec = require('child_process').exec;\n\nvar me = 'my_username';\n\nexec(\"who -q\", function(error, stdout, stderr) {\n\n    // Exit if sessions with my username are found\n    if(stdout.indexOf(me) > -1)\n        process.exit(1);\n\n    var TWILIO_ACCOUNT_SID = process.env['TWILIO_ACCOUNT_SID'];\n    var TWILIO_AUTH_TOKEN  = process.env['TWILIO_AUTH_TOKEN'];\n\n    // Phone numbers\n    var MY_NUMBER = '+xxx';\n    var BOSS_NUMBER = '+xxx';\n\n    // Excuses\n    var excuses = [\n        'Locked out',\n        'Pipes broke',\n        'Food poisoning',\n        'Not feeling well'\n    ];\n\n    // Generate BS message\n    var excuse = excuses[Math.floor(Math.random() * excuses.length)];\n    var textMessage = 'Gonna work from home. ' + excuse;\n\n    var client = require('twilio')(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);\n\n    // Shoot text\n    client.messages.create({\n        body: textMessage,\n        to: BOSS_NUMBER,\n        from: MY_NUMBER\n    }, function(error, message) {\n        if(error)\n            console.log('Failed to send SMS: ' + error.message);\n        else {\n            var currentdate = new Date();\n\n            console.log('Message sent at: '+ (currentdate.getMonth() + 1) + '/'\n                + currentdate.getDate()  + '/'\n                + currentdate.getFullYear() + ' '\n                + currentdate.getHours() + ':'\n                + currentdate.getMinutes() + ':'\n                + currentdate.getSeconds() + '| Excuse: ' + excuse);\n        }\n    });\n});\n"
  },
  {
    "path": "nodejs/kumar_asshole.js",
    "content": "#!/usr/bin/env node\n\n/* Before running:\n        npm install nodemailer\n        npm install imap\n\nI realize this is long. IMAP can only fetch emails and nodemailer can only\nsend. Could try implementing with Gmail Node API later.\n*/\n\nvar GMAIL_USERNAME = process.env['GMAIL_USERNAME'];\nvar GMAIL_PASSWORD = process.env['GMAIL_PASSWORD'];\n\nvar KUMAR_EMAIL = 'kumar.asshole@example.com';\nvar EMAIL = 'No worries mate, be careful next time';\n\n// Scan for unread email from Kumar\nvar Imap = require('imap');\nvar imap = new Imap({\n    user: GMAIL_USERNAME,\n    password: GMAIL_PASSWORD,\n    host: 'imap.gmail.com',\n    port: 993,\n    tls: true,\n    tlsOptions: { rejectUnauthorized: false }\n});\n\nfunction openInbox(cb) {\n    imap.openBox('INBOX', false, cb);\n}\n\nimap.once('ready', function() {\n    openInbox(function(err, box) {\n        if (err)\n            process.exit(1);\n\n        imap.search(['UNSEEN', ['FROM', KUMAR_EMAIL]],\n            function(err, results) {\n\n            if (err)\n                process.exit(1);\n\n            // RegEx search for keywords; ignore case\n            var kumarPattern = new RegExp(/sorry|help|wrong/i);\n\n            // IMAP dumps all headers, so need to parse and get email body\n            var MailParser = require(\"mailparser\").MailParser;\n\n            var f = imap.fetch(results, {bodies: ''});\n            f.on('message', function(msg, seqno) {\n                msg.on('body', function(stream, info) {\n                    var kumarEmail = \"\";\n\n                    stream.on('data', function(chunk) {\n                        kumarEmail += chunk.toString('utf8');\n                    });\n\n                    stream.once('end', function() {\n                        var mailparser = new MailParser();\n                        mailparser.on(\"end\", function(mail_object){\n\n                            // If the RegEx matches\n                            if(mail_object.text.match(kumarPattern)) {\n                                // Shoot email to Kumar!\n                                var nodemailer = require('nodemailer');\n\n                                // create reusable transporter object using SMTP transport\n                                var transporter = nodemailer.createTransport({\n                                    service: 'Gmail',\n                                    auth: {\n                                        user: GMAIL_USERNAME,\n                                        pass: GMAIL_PASSWORD\n                                    }\n                                });\n\n                                // setup e-mail data\n                                var mailOptions = {\n                                    from: GMAIL_USERNAME,\n                                    to: KUMAR_EMAIL,\n                                    subject: 'Database Fixes',\n                                    text: EMAIL\n                                };\n\n                                // send mail with defined transport object\n                                transporter.sendMail(mailOptions, function(error, info) {\n                                    if(error)\n                                        process.exit(1)\n                                });\n                            }\n                        });\n\n                        mailparser.write(kumarEmail);\n                        mailparser.end();\n                    });\n                });\n\n                msg.once('end', function() {\n                    // Fetched all unread from kumar\n                });\n            });\n\n            f.once('error', function(err) {\n                process.exit(1);\n            });\n\n            f.once('end', function() {\n                imap.end();\n            });\n        });\n    });\n});\n\nimap.connect();\n"
  },
  {
    "path": "nodejs/smack_my_bitch_up.js",
    "content": "#!/usr/bin/env node\n\n/* Before running:\n        npm install twilio\n*/\n\nvar exec = require('child_process').exec;\n\nvar me = 'my_username';\n\nexec(\"who -q\", function(error, stdout, stderr) {\n\n    // Exit if no sessions with my username are found\n    if(stdout.indexOf(me) == -1)\n        process.exit(1);\n\n    var TWILIO_ACCOUNT_SID = process.env['TWILIO_ACCOUNT_SID'];\n    var TWILIO_AUTH_TOKEN  = process.env['TWILIO_AUTH_TOKEN'];\n\n    // Phone numbers\n    var MY_NUMBER = '+xxx';\n    var HER_NUMBER = '+xxx';\n\n    // Reasons\n    var reasons = [\n        'Working hard',\n        'Gotta ship this feature',\n        'Someone fucked the system again'\n    ];\n\n    // Generate BS message\n    var reason = reasons[Math.floor(Math.random() * reasons.length)];\n    var textMessage = 'Late at work. ' + reason;\n\n    var client = require('twilio')(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);\n\n    // Shoot text\n    client.messages.create({\n        body: textMessage,\n        to: HER_NUMBER,\n        from: MY_NUMBER\n    }, function(error, message) {\n        if(error)\n            console.log('Failed to send SMS: ' + error.message);\n        else {\n            var currentdate = new Date();\n\n            console.log('Message sent at: '+ (currentdate.getMonth() + 1) + '/'\n                + currentdate.getDate()  + '/'\n                + currentdate.getFullYear() + ' '\n                + currentdate.getHours() + ':'\n                + currentdate.getMinutes() + ':'\n                + currentdate.getSeconds() + '| Excuse: ' + reason);\n        }\n    });\n});\n"
  },
  {
    "path": "perl/fucking-coffee.pl",
    "content": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse DateTime;\nuse YAML;\nuse Net::Telnet;\n\n# Config\nmy $conf = Load( <<'...' );\n---\ncoffee_machine_ip: 10.10.42.42\npassword: 1234\npassword_prompt: Password:\ndelay_before_brew: 17\ndelay: 24\n...\n\n# Skip on weekends\nmy $date = DateTime->now;\nif ( $date->day_of_week >= 6 ) {\n    exit;\n}\n\n# Exit early if no sessions with my username are found\nopen( my $cmd_who, '-|', 'who' ) || die \"Cannot pipe who command \". $!;\n\nmy @sessions = grep {\n    m/$ENV{'USER'}/\n} <$cmd_who>;\n\nclose $cmd_who;\n\nexit if ( scalar( @sessions ) == 0 );\n\nsleep $conf->{'delay_before_brew'};\n\nmy $con = Net::Telnet->new(\n    'Host' => $conf->{'coffee_machine_ip'},\n);\n\n$con->watifor( $conf->{'password_prompt'} );\n$con->cmd( $conf->{'password'} );\n$con->cmd( 'sys brew' );\nsleep $conf->{'delay'};\n$con->cmd( 'sys pour' );\n$con->close;\n\n"
  },
  {
    "path": "perl/hangover.pl",
    "content": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse DateTime;\nuse SMS::Send;\nuse YAML;\n\n# Config\nmy $conf = Load( <<'...' );\n---\nphone_numbers:\n  my_number: +15005550006\n  boss_number: +xxx\nreasons:\n  - Locked out\n  - Pipes broke\n  - Food poisoning\n  - Not feeling well\n...\n\nmy $date = DateTime->now;\n\n# Skip on weekends\nif ( $date->day_of_week >= 6 ) {\n    exit;\n}\n\n# Exit early if no sessions with my username are found\nopen( my $cmd_who, '-|', 'who' ) || die \"Cannot pipe who command \". $!;\n\nmy @sessions = grep {\n    m/$ENV{'USER'}/\n} <$cmd_who>;\n\nclose $cmd_who;\n\nexit if ( scalar( @sessions ) == 0 );\n\n# Load Twilio API config\nopen( my $env, '<', '../.env' ) || die \"Cannot find .env file in project root.\";\nLINE: while ( my $line = <$env> ) {\n    next LINE unless ( $line =~ m/^(TWILIO[^=]+)=(.*)(?:[\\n\\r]*)/ );\n    $conf->{'env'}->{ $1 } = $2;\n}\n\nclose $env;\n\n# Randomize excuse\nmy $reason_number = int( rand( scalar( @{ $conf->{'reasons'} } ) ) );\nmy $sms_text = \"Gonna work from home. \". $conf->{'reasons'}[ $reason_number ];\n\n# Create an object. There are three required values:\nmy $sender = SMS::Send->new('Twilio',\n    _accountsid => $conf->{'env'}->{'TWILIO_ACCOUNT_SID'},\n    _authtoken  => $conf->{'env'}->{'TWILIO_AUTH_TOKEN'},\n    _from       => $conf->{'phone_numbers'}->{'my_number'},\n);\n\n# Send a message to me\nmy $sent = $sender->send_sms(\n    text => $sms_text,\n    to   => $conf->{'phone_numbers'}->{'boss_number'},\n);\n\n# Did it send?\nif ( $sent ) {\n    print \"Sent message.\\n\";\n} else {\n    print \"Message failed.\\n\";\n}\n\n"
  },
  {
    "path": "perl/kumar-asshole.pl",
    "content": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse YAML;\nuse DateTime;\nuse Mail::Webmail::Gmail;\n\n# Config\nmy $conf = Load( <<'...' );\n---\nkumar_mail: kumar.a@example.com\ndatabase_regex: \\S+_staging\nkeywords_regex: sorry|help|wrong\nbackup_path: /home/backups/databases/\n...\n$conf->{'database_regex'} = qr/ ( $conf->{'database_regex'} ) /x;\n$conf->{'keywords_regex'} = qr/ ( $conf->{'keywords_regex'} ) /x;\n\nmy $date = DateTime->now->subtract(\n    'days' => 1\n);\n\n# Load GMail API config\nopen( my $env, '<', '../.env' ) || die \"Cannot find .env file in project root.\";\nLINE: while ( my $line = <$env> ) {\n    next LINE unless ( $line =~ m/^(GMAIL[^=]+)=(.*)(?:[\\n\\r]*)/ );\n    $conf->{'env'}->{ $1 } = $2;\n}\n\nclose $env;\n\nmy $gmail = Mail::Webmail::Gmail->new(\n    username => $conf->{'env'}->{'GMAIL_USERNAME'},\n    password => $conf->{'env'}->{'GMAIL_PASSWORD'},\n    encrypt_session => 1,\n);\n\nmy $messages = $gmail->get_messages( label => $Mail::Webmail::Gmail::FOLDERS{ 'INBOX' } );\ndie \"Cannot fetch emails: \". $gmail->error_msg();\n\nMESSAGE: foreach my $message ( @{ $messages } ) {\n    unless (\n        ( $message->{ 'new' } )\n        && ( $message->{'sender_email'} eq $conf->{'kumars_email'} )\n        && ( $message->{'body'} =~ m/$conf->{'keywords_regex'}/ )\n        && ( $message->{'body'} =~ m/$conf->{'database_regex'}/ )\n    ) {\n        print \"Skipping mail from=[\". $message->{'sender_email'}.\"] subject=[\". $message->{'subject'} .\"]\\n\";\n        next MESSAGE;\n    }\n    exit 1;\n\n    my $database = $1;\n    my $backup_file = $conf->{'backup_path'} . $database .'-'. $date->ymd() .'.gz';\n\n    unless ( -f $backup_file ) {\n        die 'Cannot find backup file=['. $backup_file .\"]\\n\";\n    }\n\n    print 'Restoring database=['. $database .'] from day=['. $date->ymd() .'] from file=['. $backup_file .\"]\\n\";\n\n    # Restore DB\n    system( 'gunzip -c '. $backup_file .' | psql '. $database );\n    die \"Error while restoring the database=[\". $database .\"] from file=[\". $backup_file .\"]\" if ( $? >> 8 );\n\n    # Mark as read, add label, reply\n    $gmail->edit_labels(\n        'label' => 'Database fixes',\n        'action' => 'add',\n        'msgid' => $message->{'id'}\n    );\n\n    $gmail->send_message(\n        'to' => $conf->{'kumars_email'},\n        'subject' => 'RE: '. $message->{'subject'},\n        'msgbody' => \"No problem. I've fixed it. \\n\\n Please be careful next time.\",\n    );\n\n    $gmail->edit_labels(\n        'label' => 'unread',\n        'action' => 'remove',\n        'msgid' => $message->{'id'}\n    );\n\n}\n\n"
  },
  {
    "path": "perl/smack-my-bitch-up.pl",
    "content": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse DateTime;\nuse SMS::Send;\nuse YAML;\n\n# Config\nmy $conf = Load( <<'...' );\n---\nphone_numbers:\n  my_number: +15005550006\n  her_number: +xxx\nreasons:\n  - Working hard\n  - Gotta ship this feature\n  - Someone fucked the system again\n...\n\nmy $date = DateTime->now;\n\n# Skip on weekends\nif ( $date->day_of_week >= 6 ) {\n    exit;\n}\n\n# Exit early if no sessions with my username are found\nopen( my $cmd_who, '-|', 'who' ) || die \"Cannot pipe who command \". $!;\n\nmy @sessions = grep {\n    m/$ENV{'USER'}/\n} <$cmd_who>;\n\nclose $cmd_who;\n\nexit if ( scalar( @sessions ) == 0 );\n\n# Load Twilio API config\nopen( my $env, '<', '../.env' ) || die \"Cannot find .env file in project root.\";\nLINE: while ( my $line = <$env> ) {\n    next LINE unless ( $line =~ m/^(TWILIO[^=]+)=(.*)(?:[\\n\\r]*)/ );\n    $conf->{'env'}->{ $1 } = $2;\n}\n\nclose $env;\n\n# Randomize excuse\nmy $reason_number = int( rand( scalar( @{ $conf->{'reasons'} } ) ) );\nmy $sms_text = \"Late at work. \". $conf->{'reasons'}[ $reason_number ];\n\n# Create an object. There are three required values:\nmy $sender = SMS::Send->new('Twilio',\n    _accountsid => $conf->{'env'}->{'TWILIO_ACCOUNT_SID'},\n    _authtoken  => $conf->{'env'}->{'TWILIO_AUTH_TOKEN'},\n    _from       => $conf->{'phone_numbers'}->{'my_number'},\n);\n\n# Send a message to me\nmy $sent = $sender->send_sms(\n    text => $sms_text,\n    to   => $conf->{'phone_numbers'}->{'her_number'},\n);\n\n# Did it send?\nif ( $sent ) {\n    print \"Sent message.\\n\";\n} else {\n    print \"Message failed.\\n\";\n}\n\n"
  },
  {
    "path": "php/composer.json",
    "content": "{\n    \"require\": {\n        \"bestnetwork/telnet\": \"^1.0\",\n        \"vlucas/phpdotenv\": \"^2.0\",\n        \"twilio/sdk\": \"^4.6\"\n    }\n}\n"
  },
  {
    "path": "php/fucking_coffee.php",
    "content": "#!/usr/bin/env php\n<?php\n\nrequire 'vendor/autoload.php';\n\nuse Bestnetwork\\Telnet\\TelnetClient;\n\n(strpos(exec('who'), getenv('USER')) !== false) or exit('no session');\nsleep(17);\n$con = new TelnetClient('10.10.42.42');\n$con->execute('1234', 'Password: ');\n$con->execute('sys brew');\nsleep(24);\n$con->execute('sys pour');\n"
  },
  {
    "path": "php/hangover.php",
    "content": "#!/usr/bin/env php\n<?php\n\nrequire 'vendor/autoload.php';\n\n(new Dotenv\\Dotenv(__DIR__))->load();\n(strpos(exec('who'), getenv('USER')) === false) or exit('session found');\n\n$my_number = '+xxx';\n$number_of_boss = '+xxx';\n$excuse = ['Locked out', 'Pipes broke', 'Food poisoning', 'Not feeling well'];\n$excuse = $excuse[array_rand($excuse)];\n\n$twilio = new Services_Twilio(getenv('TWILIO_ACCOUNT_SID'), getenv('TWILIO_AUTH_TOKEN'));\n$twilio->account->messages->sendMessage(\n\t$my_number,\n\t$number_of_boss,\n\t\"Gonna work from home. {$excuse}\"\n);\n\necho \"Message sent at: #\".date('Y-m-d').\" | Excuse: {$excuse}\";\n"
  },
  {
    "path": "php/smack_my_bitch_up.php",
    "content": "#!/usr/bin/env php\n<?php\n\nrequire 'vendor/autoload.php';\n(new Dotenv\\Dotenv(__DIR__))->load();\n\n(strpos(exec('who'), getenv('USER')) !== false) or exit('no session');\n\n// Phone numbers\n$my_number = '+xxx';\n$her_number = '+xxx';\n\n$reasons = [\n\t'Working hard',\n\t'Gotta ship this feature',\n\t'Someone fucked up the system again'\n];\n\n$rand = rand(0,count($reasons)-1);\n$random_reason = $reasons[$rand];\n\n$message = 'Late at work. '.$random_reason;\n\n// Send a text message\n$twilio = new Services_Twilio(getenv('TWILIO_ACCOUNT_SID'), getenv('TWILIO_AUTH_TOKEN'));\n$twilio->account->messages->sendMessage(\n        $my_number,\n        $her_number,\n        $message\n);\n\necho 'Message sent at: #'.date('Y-m-d').' | Reason: '.$random_reason;\n"
  },
  {
    "path": "powershell/fucking_coffee.psm1",
    "content": "<#\n.SYNOPSIS\n    Simple script to connect to a coffee part using TelNet then issue specific commands that\n\tbrew and pour a cup of coffee for the user.\n.DESCRIPTION\n    This script was converted using the ruby version of the fucking_coffee script. In this script,\n    I left the use of environment variables since its only use was to determine if the user was\n    still logged in to the system.  Per issue #42 (https://github.com/NARKOZ/hacker-scripts/issues/42)\n    I left the password string hard coded until a decision is made by NARKOZ, the project owner, as\n    to how the information should be stored.\n.OUTPUT\n    None\n.NOTES\n    Author:            Tyler Hughes\n    Twitter:           @thughesIT\n    Blog:              http://tylerhughes.info/\n\n    Changelog:\n       1.0             Initial Release\n#>\n\nFunction Fucking-Coffee\n{\n    # Exit early if no sessions with my username are found\n    if ($env:Username.Count > 0) {\n        return\n    }\n\n    $coffee_machine_ip = '10.10.42.42'\n    $password = '1234'\n\n    Start-Sleep -s 17\n\n    $socket = New-Object System.Net.Sockets.TcpClient($coffee_machine_ip)\n    if ($socket) {\n        $stream = $connection.GetStream()\n        $Writer = New-Object System.IO.StreamWriter($Stream)\n        $Buffer = New-Object System.Byte[] 1024\n        $Encoding = New-Object System.Text.AsciiEncoding\n\n        # Start issuing the commands\n        Send-TelNetCommands($Writer, $password, 1)\n        Send-TelNetCommands($Writer, \"sys brew\", 24)\n        Send-TelNetCommands($Writer, \"sys pour\", 4)\n\n        $socket.Close()\n    }\n}\n\nFunction Send-TelNetCommands\n{\n    Param (\n        [Parameter(ValueFromPipeline=$false)]\n        [System.IO.StreamWriter]$writer,\n        [String]$command,\n        [int]$WaitTime\n    )\n\n    $writer.WriteLine($command)\n    $writer.Flush()\n    Start-Sleep -Milliseconds $WaitTime\n}\n"
  },
  {
    "path": "powershell/hangover.psm1",
    "content": "<#\n.SYNOPSIS\n    Simple script to SMS a supervisor informing them you will be working from home\n    on the day this script is used.\n.DESCRIPTION\n    This script was converted using the ruby version of the hangover script. However, the ruby\n    version used environment variables to hold the user's account information. Due to issue #42\n    (https://github.com/NARKOZ/hacker-scripts/issues/42) I opted to hard code the strings at\n    this time until a decision is made by NARKOZ, the project owner, as the how the information\n    should be stored.\n\n    This script also uses Twilio to send the SMS messages. The from number MUST be a valid Twilio\n    phone number. The to number can be any outgoing number.\n.OUTPUT\n    This script will output an error message to the PowerShell window if it fails\n    to send the message.\n.NOTES\n    Author:            Tyler Hughes\n    Twitter:           @thughesIT\n    Blog:              http://tylerhughes.info/\n\n    Changelog:\n       1.0             Initial Release\n#>\nFunction Hangover\n{\n  # Phone numbers (Must include country code and area code)\n  $from = '+XXXXXXXXXXX'\n  $to = '+XXXXXXXXXXX'\n\n  # Twilio API Information\n  $twilio_base_url = 'https://api.twilio.com/2010-04-01'\n  $twilio_account_sid = 'XXXXXXXXXXXXXXXXXXX'\n  $twilio_auth_token = 'XXXXXXXXXXXXXXXXXX'\n\n  $password = ConvertTo-SecureString -AsPlainText $twilio_auth_token -Force\n  $credentials = New-Object System.Management.Automation.PSCredential($twilio_account_sid, $password)\n\n  # Get the message to send\n  $excuses =\n    'Locked out',\n    'Pipes broke',\n    'Food poisoning',\n    'Not feeling well'\n\n  $excuse = $excuses | Get-Random\n  $message = \"$excuse. Going to work from home today.\"\n  $body = @{\n    From = $from;\n    To = $to;\n    Body = $message;\n  }\n\n  # Send the message and log any errors\n  $uri = \"$twilio_base_url/Accounts/\" + $credentials.UserName + \"/SMS/Messages\"\n\n  try {\n    $response = Invoke-RestMethod -Method Post -Uri $uri -Body $body -Credential $credentials\n  }\n  catch {\n    $time = Get-Date -format u\n    Write-Host $time \" - Failed to send message: \" $message\n  }\n}"
  },
  {
    "path": "powershell/smack_my_bitch_up.ps1",
    "content": "$DAYOFWEEK = (Get-Date).DayOfWeek.value__;\n\n# Skip on weekends\nif ($DAYOFWEEK -eq 6 -or $DAYOFWEEK -eq 7) {\n    return\n}\n\n# Exit early if no sessions with my username are found\nif (-not (QWINSTA | FINDSTR $env:USERNAME)) {\n    return\n}\n\n# Phone numbers\n$MY_NUMBER='+xxx'\n$HER_NUMBER='+xxx'\n\n$REASONS =\n  'Working hard',\n  'Gotta ship this feature',\n  'Someone fucked the system again'\n$reason = $REASONS | Get-Random\n$message = \"Late at work. $reason.\"\n\n$API_URL = \"https://api.twilio.com/2010-04-01/Accounts/$env:TWILIO_ACCOUNT_SID/Messages\"\n$BASE64AUTHINFO = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes((\"{0}:{1}\" -f $env:TWILIO_ACCOUNT_SID,$env:TWILIO_AUTH_TOKEN)))\n$body = @{\n    From = $MY_NUMBER;\n    To = $HER_NUMBER;\n    Body = $message;\n}\n\n#Send a text message and Log errors\ntry{\n    Invoke-RestMethod -Method Post -Headers @{Authorization=(\"Basic {0}\" -f $BASE64AUTHINFO)} $API_URL -Body $body > $null\n}\ncatch{\n    Write-Host \"Failed to send SMS: $_\"\n}\n"
  },
  {
    "path": "python/fucking_coffee.py",
    "content": "#!/usr/bin/env python\n\nimport sys\nimport subprocess\nimport telnetlib\nimport time\n\n# exit if no sessions with my username are found\noutput = subprocess.check_output('who')\nif 'my_username' not in output:\n    sys.exit()\n\ntime.sleep(17)\n\ncoffee_machine_ip = '10.10.42.42'\npassword = '1234'\npassword_prompt = 'Password: '\n\ncon = telnetlib.Telnet(coffee_machine_ip)\ncon.read_until(password_prompt)\ncon.write(password + \"\\n\")\n\n# Make some coffee!\ncon.write(\"sys brew\\n\")\ntime.sleep(24)\n\n# love the smell!\ncon.write(\"sys pour\\n\")\ncon.close()    \n"
  },
  {
    "path": "python/hangover.py",
    "content": "#!/usr/bin/env python\n\nimport os\nimport random\nfrom twilio.rest import TwilioRestClient\nfrom time import strftime\nimport subprocess\n\n# exit if sessions with my username are found\noutput = subprocess.check_output('who')\nif 'my_username' in output:\n    sys.exit()\n\n# returns 'None' if the key doesn't exist\nTWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID')\nTWILIO_AUTH_TOKEN  = os.environ.get('TWILIO_AUTH_TOKEN')\n\n# Phone numbers\nmy_number      = '+xxx'\nnumber_of_boss = '+xxx'\n\nexcuses = [\n  'Locked out',\n  'Pipes broke',\n  'Food poisoning',\n  'Not feeling well'\n]\n\nclient = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)\n\nclient.messages.create(\n    to=number_of_boss,\n    from_=my_number,\n    body=\"Gonna work from home. \" + random.choice(excuses)\n)\n\nprint \"Message sent at \" + strftime(\"%a, %d %b %Y %H:%M:%S\")\n"
  },
  {
    "path": "python/kumar_asshole.py",
    "content": "#!/usr/bin/env python\n\nimport gmail\nimport sys\nimport re\n\nGMAIL_USERNAME = ENV['GMAIL_USERNAME']\nGMAIL_PASSWORD = ENV['GMAIL_PASSWORD']\n\ng = gmail.login(GMAIL_USERNAME, GMAIL_PASSWORD)\n\nif not g.logged_in:\n    sys.exit()\n\nmsgs = g.inbox().mail(sender=\"kumar.a@example.com\", unread=True, prefetch=True)\n\npattern = re.compile(\"\\bsorry\\b | \\bhelp\\b | \\bwrong\\b \", flags=re.I)\n\nfor msg in msgs:\n    if pattern.match(msg.body):\n        msg.label(\"Database fixes\")\n        msg.reply(\"No problem. I've fixed it. \\n\\n Please be careful next time.\")\n"
  },
  {
    "path": "python/smack_my_bitch_up.py",
    "content": "#!/usr/bin/env python\n\nimport os\nimport random\nfrom twilio.rest import TwilioRestClient\nimport subprocess\nimport sys\nfrom time import strftime\n\n# exit if no sessions with my username are found\noutput = subprocess.check_output('who')\nif 'my_username' not in output:\n    sys.exit()\n\n# returns 'None' if the key doesn't exist\nTWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID')\nTWILIO_AUTH_TOKEN  = os.environ.get('TWILIO_AUTH_TOKEN')\n\n# Phone numbers\nmy_number  = '+xxx'\nher_number = '+xxx'\n\nreasons = [\n  'Working hard',\n  'Gotta ship this feature',\n  'Someone fucked the system again'\n]\n\nclient = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)\n\nclient.messages.create(\n    to=her_number,\n    from_=my_number,\n    body=\"Late at work. \" + random.choice(reasons)\n)\n\nprint \"Message sent at \" + strftime(\"%a, %d %b %Y %H:%M:%S\")\n"
  },
  {
    "path": "python3/fucking_coffee.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport telnetlib\nimport time\n\nfrom hackerutils import sh\n\nCOFFEE_MACHINE_ADDR = '10.10.42.42'\nCOFFEE_MACHINE_PASS = '1234'\nCOFFEE_MACHINE_PROM = 'Password: '\n\n\ndef main():\n    # Exit early if no sessions with my_username are found.\n    if not any(s.startswith(b'my_username ') for s in sh('who').split(b'\\n')):\n        return\n\n    time.sleep(17)\n\n    conn = telnetlib.Telnet(host=COFFEE_MACHINE_ADDR)\n    conn.open()\n    conn.expect([COFFEE_MACHINE_PROM])\n    conn.write(COFFEE_MACHINE_PASS)\n\n    conn.write('sys brew')\n    time.sleep(24)\n\n    conn.write('sys pour')\n    conn.close()\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "python3/hackerutils.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pathlib\nimport subprocess\n\nfrom dotenv import Dotenv\n\n\ndef get_dotenv(filename='.env'):\n    return Dotenv(str(pathlib.Path(__file__).parent / filename))\n\n\ndef sh(*args):\n    proc = subprocess.Popen(args, stdout=subprocess.PIPE)\n    stdout, _ = proc.communicate()\n    return stdout\n\n\ndef get_log_path(name):\n    path = pathlib.Path(__file__).parent / 'logs' / name\n    path.parent.mkdir(parents=True, exist_ok=True)\n    return path\n"
  },
  {
    "path": "python3/hangover.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport random\n\nfrom twilio import TwilioRestException\nfrom twilio.rest import TwilioRestClient\n\nfrom hackerutils import get_dotenv, get_log_path, sh\n\ndotenv = get_dotenv()\n\nTWILIO_ACCOUNT_SID = dotenv['TWILIO_ACCOUNT_SID']\nTWILIO_AUTH_TOKEN = dotenv['TWILIO_AUTH_TOKEN']\n\nLOG_FILE_PATH = get_log_path('hangover.txt')\n\n\ndef main():\n    # Exit early if any session with my_username is found.\n    if any(s.startswith(b'my_username ') for s in sh('who').split(b'\\n')):\n        return\n\n    client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)\n\n    # Phone numbers.\n    my_number = '+xxx'\n    number_of_boss = '+xxx'\n\n    excuses = [\n        'Locked out',\n        'Pipes broke',\n        'Food poisoning',\n        'Not feeling well',\n    ]\n\n    try:\n        # Send a text message.\n        client.messages.create(\n            to=number_of_boss,\n            from_=my_number,\n            body='Gonna work from home. ' + random.choice(excuses),\n        )\n    except TwilioRestException as e:\n        # Log errors.\n        with LOG_FILE_PATH.open('a') as f:\n            f.write('Failed to send SMS: {}'.format(e))\n        raise\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "python3/kumar_asshole.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport re\n\nimport gmail\nimport yagmail\n\nfrom hackerutils import get_dotenv\n\ndotenv = get_dotenv()\n\nGMAIL_USERNAME = dotenv['GMAIL_USERNAME']\nGMAIL_PASSWORD = dotenv['GMAIL_PASSWORD']\n\nKUMAR_EMAIL = 'kumar.a@example.com'\nKEYWORDS_REGEX = re.compile(r'sorry|help|wrong', re.IGNORECASE)\n\nREPLY_BODY = \"No problem. I've fixed it. \\n\\nPlease be careful next time.\"\n\n\nyagmail.register(GMAIL_USERNAME, GMAIL_PASSWORD)\n\n\ndef send_reply(subject):\n    yag = yagmail.SMTP(GMAIL_USERNAME)\n    yag.send(\n        to=KUMAR_EMAIL,\n        subject='RE: {}'.format(subject),\n        contents=REPLY_BODY,\n    )\n\n\ndef main():\n    g = gmail.login(GMAIL_USERNAME, GMAIL_PASSWORD)\n    for mail in g.inbox().mail(unread=True, sender=KUMAR_EMAIL, prefetch=True):\n        if KEYWORDS_REGEX.search(mail.body):\n            # Restore DB and send a reply.\n            mail.add_label('Database fixes')\n            send_reply(mail.subject)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "python3/requirements.txt",
    "content": "dotenv\ntwilio\nyagmail\ngit+https://github.com/charlierguo/gmail\n"
  },
  {
    "path": "python3/smack_my_bitch_up.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport random\n\nfrom twilio import TwilioRestException\nfrom twilio.rest import TwilioRestClient\n\nfrom hackerutils import get_dotenv, get_log_path, sh\n\ndotenv = get_dotenv()\n\nTWILIO_ACCOUNT_SID = dotenv['TWILIO_ACCOUNT_SID']\nTWILIO_AUTH_TOKEN = dotenv['TWILIO_AUTH_TOKEN']\n\nLOG_FILE_PATH = get_log_path('smack_my_bitch_up.txt')\n\n\ndef main():\n    # Exit early if no sessions with my_username are found.\n    if not any(s.startswith(b'my_username ') for s in sh('who').split(b'\\n')):\n        return\n\n    client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)\n\n    # Phone numbers.\n    my_number = '+xxx'\n    her_number = '+xxx'\n\n    reasons = [\n        'Working hard',\n        'Gotta ship this feature',\n        'Someone fucked the system again',\n    ]\n\n    try:\n        # Send a text message.\n        client.messages.create(\n            to=her_number,\n            from_=my_number,\n            body='Late at work. ' + random.choice(reasons),\n        )\n    except TwilioRestException as e:\n        # Log errors.\n        with LOG_FILE_PATH.open('a') as f:\n            f.write('Failed to send SMS: {}'.format(e))\n        raise\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "scala/fucking-coffee.scala",
    "content": "/*******************************************\n *\n * Get Ammonite (http://lihaoyi.github.io/Ammonite/#Ammonite-Shell): \n *  $ mkdir ~/.ammonite; curl -L -o ~/.ammonite/predef.scala http://git.io/vR04f\n *  $ curl -L -o amm http://git.io/vR08A; chmod +x amm\n *\n * Run script\n *  $ ./amm fucking-coffee.scala\n *\n *******************************************/\n\nimport java.net._\nimport java.io._\nimport ammonite.ops._\nimport ammonite.ops.ImplicitWd._\n\nval coffeeMachineIP = \"10.10.42.42\"\nval password = \"1234\"\nval passwordPrompt = \"Password: \"\nval delayBeforeBrew = 17\nval delay = 24\n\nif ((%%who \"-q\").out.string.contains(sys.props(\"user.name\"))) {\n\n  val telnet = new Socket(coffeeMachineIP, 23)\n  val out = new PrintWriter(telnet.getOutputStream, true)\n  val in = new BufferedReader(new InputStreamReader(telnet.getInputStream))\n\n  println(s\"Wait for $delayBeforeBrew seconds\")\n  Thread.sleep(delayBeforeBrew * 1000);\n\n  if(in.readLine == passwordPrompt){\n    out.println(password)\n    \n    out.println(\"sys brew\")\n    Thread.sleep(delay * 1000)\n    out.println(\"sys pour\")\n\n  }\n\n  out.close()\n  in.close()\n  telnet.close()\n  \n}"
  },
  {
    "path": "smack-my-bitch-up.sh",
    "content": "#!/bin/sh -e\n\n# Exit early if no sessions with my username are found\nif ! who | grep -wq $USER; then\n  exit\nfi\n\n# Phone numbers\nMY_NUMBER='+xxx'\nHER_NUMBER='+xxx'\n\nREASONS=(\n  'Working hard'\n  'Gotta ship this feature'\n  'Someone fucked the system again'\n)\nrand=$[ $RANDOM % ${#REASONS[@]} ]\n\nRANDOM_REASON=${REASONS[$rand]}\nMESSAGE=\"Late at work. \"$RANDOM_REASON\n\n# Send a text message\nRESPONSE=`curl -fSs -u \"$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN\" \\\n  -d \"From=$MY_NUMBER\" -d \"To=$HER_NUMBER\" -d \"Body=$MESSAGE\" \\\n  \"https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages\"`\n\n# Log errors\nif [ $? -gt 0 ]; then\n  echo \"Failed to send SMS: $RESPONSE\"\n  exit 1\nfi\n"
  },
  {
    "path": "smack_my_bitch_up.rb",
    "content": "#!/usr/bin/env ruby\n\n# Exit early if no sessions with my username are found\nexit unless `who -q`.include? ENV['USER']\n\nrequire 'dotenv'\nrequire 'twilio-ruby'\n\nDotenv.load\n\nTWILIO_ACCOUNT_SID = ENV['TWILIO_ACCOUNT_SID']\nTWILIO_AUTH_TOKEN  = ENV['TWILIO_AUTH_TOKEN']\n\n@twilio = Twilio::REST::Client.new TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN\n\n# Phone numbers\nmy_number  = '+xxx'\nher_number = '+xxx'\n\nreason = [\n  'Working hard',\n  'Gotta ship this feature',\n  'Someone fucked the system again'\n].sample\n\n# Send a text message\n@twilio.messages.create(\n  from: my_number, to: her_number, body: \"Late at work. #{reason}\"\n)\n\n# Log this\nputs \"Message sent at: #{Time.now} | Reason: #{reason}\"\n"
  }
]