#!/bin/bash

# script for using your linux laptops camera as webcam
# for upload to work, you must add your public SSH key to PUBLISHING_HOSTs ~/.ssh/authorized_keys
# dependencies: ssh scp fswebcam

# conf

INTERVAL_IN_SECONDS=30
PUBLISHING_HOST=juks@juks.alkohol.ee
PUBLISHING_DIR=/home/juks/public_html/cam

# constants

IMG0=index.jpg
IMG1=new.jpg
INDEX=index.html
TXT_NEXT="Interval of photos: "$INTERVAL_IN_SECONDS" seconds."

# generate and upload main page

cat <<EOF > $INDEX
<html>
<head>
<title>Cam</title>
<meta http-equiv=Content-Type content="text/html; charset=UTF-8">
<meta http-equiv="Refresh" content="$INTERVAL_IN_SECONDS">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate, max-age=0"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="0"/>
<style>
html, body {
    background-color: black;
    height: 100%;
    margin: 0;
    padding: 0;
}

img {
    padding: 0;
    display: block;
    margin: 0 auto;
    max-height: 100%;
    max-width: 100%;
}
</style>
</head>
<body>
<a href="$IMG0"><img src="$IMG0" title="$TXT_NEXT"/></a>
</body>
</html>
EOF
scp $INDEX $PUBLISHING_HOST:$PUBLISHING_DIR

# run webcam

for (( ; ; ))
do
   fswebcam --banner-colour \#FF000000 --line-colour \#FF000000 --text-colour \#FF00FF --top-banner --shadow --font :20 -r 1280x720 $IMG1
   scp $IMG1 $PUBLISHING_HOST:$PUBLISHING_DIR
   ssh $PUBLISHING_HOST "cd "$PUBLISHING_DIR" ; mv "$IMG1" "$IMG0
   mv $IMG1 $IMG0
   echo
   echo "New image uploaded. "$TXT_NEXT" Press CTRL+C to stop webcam..."
   echo
   sleep $INTERVAL_IN_SECONDS
done
